'use client';

import { useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Loader2, Minus, Plus } from 'lucide-react';
import { formatNumber } from '@/lib/utils/amount';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { CurrencyInput } from '@/components/ui/currency-input';
import { FormField } from '@/components/molecules/FormField';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { CardTransaction, JournalEntryItem } from './types';
import { DEDUCTION_OPTIONS } from './types';
import { AccountSubjectSelect } from '@/components/accounting/common';
import { saveJournalEntries } from './actions';

interface JournalEntryModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  transaction: CardTransaction | null;
  onSuccess: () => void;
}

function createEmptyItem(transaction: CardTransaction | null): JournalEntryItem {
  return {
    supplyAmount: transaction?.supplyAmount || 0,
    taxAmount: transaction?.taxAmount || 0,
    totalAmount: transaction?.totalAmount || 0,
    accountSubject: '',
    deductionType: 'deductible',
    vendorName: '',
    description: '',
    memo: '',
  };
}

export function JournalEntryModal({ open, onOpenChange, transaction, onSuccess }: JournalEntryModalProps) {
  const [items, setItems] = useState<JournalEntryItem[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 모달 열릴 때 초기 항목 설정
  const handleOpenChange = useCallback((isOpen: boolean) => {
    if (isOpen && transaction) {
      setItems([createEmptyItem(transaction)]);
    }
    onOpenChange(isOpen);
  }, [transaction, onOpenChange]);

  const updateItem = useCallback((index: number, key: keyof JournalEntryItem, value: string | number) => {
    setItems(prev => {
      const updated = [...prev];
      const item = { ...updated[index], [key]: value };
      // 합계금액 자동 계산
      if (key === 'supplyAmount' || key === 'taxAmount') {
        const supply = key === 'supplyAmount' ? (value as number) : item.supplyAmount;
        const tax = key === 'taxAmount' ? (value as number) : item.taxAmount;
        item.totalAmount = supply + tax;
      }
      updated[index] = item;
      return updated;
    });
  }, []);

  const addItem = useCallback(() => {
    setItems(prev => [...prev, createEmptyItem(null)]);
  }, []);

  const removeItem = useCallback((index: number) => {
    setItems(prev => prev.filter((_, i) => i !== index));
  }, []);

  const journalTotal = items.reduce((sum, item) => sum + item.totalAmount, 0);

  const handleSave = useCallback(async () => {
    if (!transaction) return;

    const hasEmptyAccount = items.some(item => !item.accountSubject);
    if (hasEmptyAccount) {
      toast.error('모든 분개 항목에 계정과목을 선택해주세요.');
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await saveJournalEntries(transaction.id, items);
      if (result.success) {
        toast.success('분개가 저장되었습니다.');
        onOpenChange(false);
        onSuccess();
      } else {
        toast.error(result.error || '분개 저장에 실패했습니다.');
      }
    } catch {
      toast.error('분개 저장 중 오류가 발생했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  }, [transaction, items, onOpenChange, onSuccess]);

  if (!transaction) return null;

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>거래 분개</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          {/* 거래 정보 (읽기 전용 - FormField 대상 아님) */}
          <div className="border rounded-lg p-4 bg-muted/30 space-y-3">
            <h4 className="font-medium text-sm">거래 정보</h4>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label className="text-xs text-muted-foreground">가맹점</Label>
                <p className="text-sm font-medium mt-0.5">{transaction.merchantName}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">사용일시</Label>
                <p className="text-sm font-medium mt-0.5">{transaction.usedAt}</p>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <Label className="text-xs text-muted-foreground">공급가액</Label>
                <p className="text-sm font-medium mt-0.5">{formatNumber(transaction.supplyAmount)}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">세액</Label>
                <p className="text-sm font-medium mt-0.5">{formatNumber(transaction.taxAmount)}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">합계금액</Label>
                <p className="text-sm font-medium mt-0.5">{formatNumber(transaction.totalAmount)}</p>
              </div>
            </div>
          </div>

          {/* 분개 항목 목록 */}
          {items.map((item, index) => (
            <div key={index} className="border rounded-lg p-4 space-y-3 relative">
              <div className="flex items-center justify-between">
                <h4 className="font-medium text-sm">분개 항목</h4>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7"
                  onClick={() => removeItem(index)}
                  disabled={items.length <= 1}
                >
                  <Minus className="h-4 w-4" />
                </Button>
              </div>

              {/* 공급가액 + 세액 + 합계금액 */}
              <div className="grid grid-cols-3 gap-3">
                <div>
                  <Label className="text-xs">공급가액</Label>
                  <CurrencyInput
                    value={item.supplyAmount}
                    onChange={(v) => updateItem(index, 'supplyAmount', v ?? 0)}
                    className="mt-1 h-8 text-sm"
                    showCurrency={false}
                  />
                </div>
                <div>
                  <Label className="text-xs">세액</Label>
                  <CurrencyInput
                    value={item.taxAmount}
                    onChange={(v) => updateItem(index, 'taxAmount', v ?? 0)}
                    className="mt-1 h-8 text-sm"
                    showCurrency={false}
                  />
                </div>
                <div>
                  <Label className="text-xs">합계금액</Label>
                  <CurrencyInput
                    value={item.totalAmount}
                    onChange={() => {}}
                    disabled
                    className="mt-1 h-8 text-sm bg-muted/50"
                    showCurrency={false}
                  />
                </div>
              </div>

              {/* 계정과목 + 공제 + 증빙/판매자상호 */}
              <div className="grid grid-cols-3 gap-3">
                <div>
                  <Label className="text-xs">계정과목</Label>
                  <div className="mt-1">
                    <AccountSubjectSelect
                      value={item.accountSubject}
                      onValueChange={(v) => updateItem(index, 'accountSubject', v)}
                      placeholder="선택"
                      size="sm"
                    />
                  </div>
                </div>
                {/* Select - FormField 예외 */}
                <div>
                  <Label className="text-xs">공제</Label>
                  <Select
                    value={item.deductionType}
                    onValueChange={(v) => updateItem(index, 'deductionType', v)}
                  >
                    <SelectTrigger className="mt-1 h-8 text-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {DEDUCTION_OPTIONS.map(opt => (
                        <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <FormField
                  label="증빙/판매자상호"
                  value={item.vendorName}
                  onChange={(v) => updateItem(index, 'vendorName', v)}
                  placeholder="내용"
                  inputClassName="h-8 text-sm"
                />
              </div>

              {/* 내역 + 메모 */}
              <div className="grid grid-cols-2 gap-3">
                <FormField
                  label="내역"
                  value={item.description}
                  onChange={(v) => updateItem(index, 'description', v)}
                  placeholder="내역"
                  inputClassName="h-8 text-sm"
                />
                <FormField
                  label="메모"
                  value={item.memo}
                  onChange={(v) => updateItem(index, 'memo', v)}
                  inputClassName="h-8 text-sm"
                />
              </div>
            </div>
          ))}

          {/* 분개 항목 추가 버튼 */}
          <Button
            variant="outline"
            className="w-full"
            onClick={addItem}
          >
            <Plus className="h-4 w-4 mr-2" />
            분개 항목 추가
          </Button>

          {/* 분개 합계 */}
          <div className="bg-muted/50 rounded-lg p-3 flex items-center justify-between">
            <span className="text-sm font-medium">분개 합계</span>
            <span className="text-lg font-bold">{formatNumber(journalTotal)}원</span>
          </div>
        </div>

        <DialogFooter className="gap-3">
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
            취소
          </Button>
          <Button onClick={handleSave} disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                저장 중...
              </>
            ) : (
              '저장'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
