'use client';

import { useState, useCallback } from 'react';
import { CreditCard, Download, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import type { SubscriptionInfo } from './types';
import { PLAN_LABELS } from './types';
import { requestDataExport, cancelSubscription } from './actions';
import { formatAmountWon as formatCurrency, formatNumber } from '@/lib/utils/amount';

// ===== 기본 저장공간 (10GB) =====
const DEFAULT_STORAGE_LIMIT = 10 * 1024 * 1024 * 1024; // 10GB in bytes

// ===== 기본값 (API 실패시 사용) =====
const defaultSubscription: SubscriptionInfo = {
  lastPaymentDate: '',
  nextPaymentDate: '',
  subscriptionAmount: 0,
  plan: 'free',
  userCount: 0,
  userLimit: null,
  storageUsed: 0,
  storageLimit: DEFAULT_STORAGE_LIMIT,
  storageUsedFormatted: '0 B',
  storageLimitFormatted: '10 GB',
  apiCallsUsed: 0,
  apiCallsLimit: 10000,
};

// ===== 날짜 포맷 함수 =====
const formatDate = (dateStr: string): string => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}년 ${month}월 ${day}일`;
};

interface SubscriptionManagementProps {
  initialData: SubscriptionInfo | null;
}

export function SubscriptionManagement({ initialData }: SubscriptionManagementProps) {
  const [subscription, setSubscription] = useState<SubscriptionInfo>(initialData || defaultSubscription);
  const [showCancelDialog, setShowCancelDialog] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [isCancelling, setIsCancelling] = useState(false);

  // ===== 자료 내보내기 =====
  const handleExportData = useCallback(async () => {
    setIsExporting(true);
    try {
      const result = await requestDataExport('all');
      if (result.success) {
        toast.success('내보내기 요청이 등록되었습니다. 완료되면 알림을 보내드립니다.');
      } else {
        toast.error(result.error || '내보내기 요청에 실패했습니다.');
      }
    } catch {
      toast.error('서버 오류가 발생했습니다.');
    } finally {
      setIsExporting(false);
    }
  }, []);

  // ===== 서비스 해지 =====
  const handleCancelService = useCallback(async () => {
    if (!subscription.id) {
      toast.error('구독 정보를 찾을 수 없습니다.');
      setShowCancelDialog(false);
      return;
    }

    setIsCancelling(true);
    try {
      const result = await cancelSubscription(subscription.id, '사용자 요청');
      if (result.success) {
        toast.success('서비스가 해지되었습니다.');
        setSubscription(prev => ({ ...prev, status: 'cancelled' }));
      } else {
        toast.error(result.error || '서비스 해지에 실패했습니다.');
      }
    } catch {
      toast.error('서버 오류가 발생했습니다.');
    } finally {
      setIsCancelling(false);
      setShowCancelDialog(false);
    }
  }, [subscription.id]);

  // ===== Progress 계산 =====
  const storageProgress = subscription.storageLimit ? (subscription.storageUsed / subscription.storageLimit) * 100 : 0;
  const apiCallsUsed = subscription.apiCallsUsed ?? 0;
  const apiCallsLimit = subscription.apiCallsLimit ?? 0;
  const apiProgress = apiCallsLimit > 0 ? (apiCallsUsed / apiCallsLimit) * 100 : 0;

  return (
    <>
      <PageLayout>
        {/* ===== 페이지 헤더 ===== */}
        <PageHeader
          title="구독관리"
          description="구독 정보를 관리합니다"
          icon={CreditCard}
        />

        {/* ===== 헤더 액션 버튼 ===== */}
        <div className="flex justify-end gap-2 mb-4">
          <Button variant="outline" onClick={handleExportData} disabled={isExporting}>
            <Download className="w-4 h-4 mr-2" />
            {isExporting ? '처리 중...' : '자료 내보내기'}
          </Button>
          <Button
            variant="outline"
            className="border-red-200 text-red-600 hover:bg-red-50 hover:border-red-300"
            onClick={() => setShowCancelDialog(true)}
            disabled={subscription.status === 'cancelled'}
          >
            서비스 해지
          </Button>
        </div>

        <div className="space-y-6">
          {/* ===== 구독 정보 카드 영역 ===== */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* 최근 결제일시 */}
            <Card>
              <CardContent className="pt-6">
                <div className="text-sm text-muted-foreground mb-1">최근 결제일시</div>
                <div className="text-2xl font-bold">
                  {formatDate(subscription.lastPaymentDate)}
                </div>
              </CardContent>
            </Card>

            {/* 다음 결제일시 */}
            <Card>
              <CardContent className="pt-6">
                <div className="text-sm text-muted-foreground mb-1">다음 결제일시</div>
                <div className="text-2xl font-bold">
                  {formatDate(subscription.nextPaymentDate)}
                </div>
              </CardContent>
            </Card>

            {/* 구독금액 */}
            <Card>
              <CardContent className="pt-6">
                <div className="text-sm text-muted-foreground mb-1">구독금액</div>
                <div className="text-2xl font-bold">
                  {formatCurrency(subscription.subscriptionAmount)}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* ===== 구독 정보 영역 ===== */}
          <Card>
            <CardContent className="pt-6">
              <div className="text-sm text-muted-foreground mb-2">구독 정보</div>

              {/* 플랜명 */}
              <h3 className="text-xl font-bold mb-6">
                {PLAN_LABELS[subscription.plan]}
              </h3>

              {/* 사용량 정보 */}
              <div className="space-y-5">
                {/* 사용자 수 */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">사용자 수</span>
                    <span className="text-sm text-blue-600">
                      {subscription.userCount}명 / {subscription.userLimit ? `${subscription.userLimit}명` : '무제한'}
                    </span>
                  </div>
                  <Progress value={subscription.userLimit ? (subscription.userCount / subscription.userLimit) * 100 : 30} className="h-2" />
                </div>

                {/* 저장 공간 */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">저장 공간</span>
                    <span className="text-sm text-blue-600">
                      {subscription.storageUsedFormatted} / {subscription.storageLimitFormatted}
                    </span>
                  </div>
                  <Progress value={storageProgress} className="h-2" />
                </div>

                {/* AI API 호출 */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">AI API 호출</span>
                    <span className="text-sm text-blue-600">
                      {formatNumber(apiCallsUsed)} / {formatNumber(apiCallsLimit)}
                    </span>
                  </div>
                  <Progress value={apiProgress} className="h-2" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </PageLayout>

      {/* ===== 서비스 해지 확인 다이얼로그 ===== */}
      <ConfirmDialog
        open={showCancelDialog}
        onOpenChange={setShowCancelDialog}
        onConfirm={handleCancelService}
        variant="destructive"
        title={
          <span className="flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-red-500" />
            서비스 해지
          </span>
        }
        description={
          <>
            모든 데이터가 삭제되며 복구할 수 없습니다.
            <br />
            <span className="font-medium text-red-600">
              정말 서비스를 해지하시겠습니까?
            </span>
          </>
        }
        confirmText="확인"
        loading={isCancelling}
      />
    </>
  );
}