'use client';

import { Plus, Trash2, Loader2 } from 'lucide-react';
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 { Checkbox } from '@/components/ui/checkbox';
import { DatePicker } from '@/components/ui/date-picker';
import { formatNumber } from '@/lib/utils/amount';
import type { ExpenseEstimateData, ExpenseEstimateItem } from './types';

interface ExpenseEstimateFormProps {
  data: ExpenseEstimateData;
  onChange: (data: ExpenseEstimateData) => void;
  isLoading?: boolean;
}

/**
 * 비용견적서 폼 — API 템플릿 필드 매칭
 * items 배열 (expectedPaymentDate, category, amount, vendor, memo)
 * + totalExpense, accountBalance, finalDifference
 */
export function ExpenseEstimateForm({ data, onChange, isLoading }: ExpenseEstimateFormProps) {

  const recalcTotals = (items: ExpenseEstimateItem[], accountBalance: number) => {
    const totalExpense = items.reduce((sum, item) => sum + (item.amount || 0), 0);
    return { totalExpense, finalDifference: accountBalance - totalExpense };
  };

  const handleItemChange = (index: number, field: keyof ExpenseEstimateItem, value: string | number | boolean) => {
    const newItems = [...data.items];
    newItems[index] = { ...newItems[index], [field]: value };
    const { totalExpense, finalDifference } = recalcTotals(newItems, data.accountBalance);
    onChange({ ...data, items: newItems, totalExpense, finalDifference });
  };

  const handleAddItem = () => {
    const newItem: ExpenseEstimateItem = {
      id: `item-${Date.now()}`,
      checked: false,
      expectedPaymentDate: '',
      category: '',
      amount: 0,
      vendor: '',
      memo: '',
    };
    onChange({ ...data, items: [...data.items, newItem] });
  };

  const handleDeleteChecked = () => {
    const remaining = data.items.filter(item => !item.checked);
    const { totalExpense, finalDifference } = recalcTotals(remaining, data.accountBalance);
    onChange({ ...data, items: remaining, totalExpense, finalDifference });
  };

  const handleAccountBalanceChange = (value: string) => {
    const accountBalance = Number(value.replace(/,/g, '')) || 0;
    const { totalExpense, finalDifference } = recalcTotals(data.items, accountBalance);
    onChange({ ...data, accountBalance, totalExpense, finalDifference });
  };

  const checkedCount = data.items.filter(i => i.checked).length;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
        <span className="text-muted-foreground">비용견적서 데이터를 불러오는 중...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-lg border p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold">비용견적서 항목</h3>
          <div className="flex items-center gap-2">
            {checkedCount > 0 && (
              <Button variant="outline" size="sm" onClick={handleDeleteChecked} className="text-red-600">
                <Trash2 className="h-4 w-4 mr-1" />
                선택 삭제 ({checkedCount})
              </Button>
            )}
            <Button variant="outline" size="sm" onClick={handleAddItem}>
              <Plus className="h-4 w-4 mr-1" />
              항목 추가
            </Button>
          </div>
        </div>

        {/* 항목 테이블 */}
        <div className="border rounded-md overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-muted/50 border-b">
                <th className="p-2 w-10 text-center">
                  <Checkbox
                    checked={data.items.length > 0 && data.items.every(i => i.checked)}
                    onCheckedChange={(checked) => {
                      const newItems = data.items.map(i => ({ ...i, checked: !!checked }));
                      onChange({ ...data, items: newItems });
                    }}
                  />
                </th>
                <th className="p-2 w-10 text-center font-medium">No.</th>
                <th className="p-2 font-medium w-36">예상 지급일</th>
                <th className="p-2 font-medium">항목</th>
                <th className="p-2 font-medium w-32 text-right">지출금액</th>
                <th className="p-2 font-medium w-28">거래처</th>
                <th className="p-2 font-medium w-32">비고</th>
              </tr>
            </thead>
            <tbody>
              {data.items.length === 0 ? (
                <tr>
                  <td colSpan={7} className="p-8 text-center text-muted-foreground">
                    항목이 없습니다. &quot;항목 추가&quot; 버튼을 눌러 추가하세요.
                  </td>
                </tr>
              ) : (
                data.items.map((item, index) => (
                  <tr key={item.id} className="border-b last:border-b-0">
                    <td className="p-2 text-center">
                      <Checkbox
                        checked={item.checked}
                        onCheckedChange={(checked) => handleItemChange(index, 'checked', !!checked)}
                      />
                    </td>
                    <td className="p-2 text-center text-muted-foreground">{index + 1}</td>
                    <td className="p-2">
                      <DatePicker
                        value={item.expectedPaymentDate}
                        onChange={(date) => handleItemChange(index, 'expectedPaymentDate', date)}
                        size="sm"
                        placeholder="날짜 선택"
                      />
                    </td>
                    <td className="p-2">
                      <Input
                        value={item.category}
                        onChange={(e) => handleItemChange(index, 'category', e.target.value)}
                        placeholder="항목명"
                        className="h-8"
                      />
                    </td>
                    <td className="p-2">
                      <CurrencyInput
                        value={item.amount || 0}
                        onChange={(v) => handleItemChange(index, 'amount', v ?? 0)}
                        className="h-8"
                        showCurrency={false}
                      />
                    </td>
                    <td className="p-2">
                      <Input
                        value={item.vendor ?? ''}
                        onChange={(e) => handleItemChange(index, 'vendor', e.target.value)}
                        placeholder="거래처"
                        className="h-8"
                      />
                    </td>
                    <td className="p-2">
                      <Input
                        value={item.memo ?? ''}
                        onChange={(e) => handleItemChange(index, 'memo', e.target.value)}
                        placeholder="비고"
                        className="h-8"
                      />
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 합계 영역 */}
        <div className="mt-4 space-y-3">
          <div className="flex items-center justify-between border-t pt-4">
            <Label className="font-semibold">지출 합계</Label>
            <span className="text-lg font-bold text-red-600">
              {formatNumber(data.totalExpense)}원
            </span>
          </div>
          <div className="flex items-center justify-between">
            <Label className="font-semibold">계좌 잔액</Label>
            <Input
              type="text"
              value={formatNumber(data.accountBalance)}
              onChange={(e) => handleAccountBalanceChange(e.target.value)}
              className="w-48 text-right h-8"
            />
          </div>
          <div className="flex items-center justify-between border-t pt-3">
            <Label className="font-semibold">최종 차액</Label>
            <span className={`text-lg font-bold ${data.finalDifference >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
              {formatNumber(data.finalDifference)}원
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
