'use client';

import { useCallback } from 'react';
import { formatNumber } from '@/lib/utils/amount';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Plus, Trash2 } from 'lucide-react';
import { createEmptyItem, TAX_TYPE_OPTIONS } from './types';
import type { TaxInvoiceItem } from './types';

interface TaxInvoiceItemTableProps {
  items: TaxInvoiceItem[];
  onItemsChange: (items: TaxInvoiceItem[]) => void;
}

export function TaxInvoiceItemTable({ items, onItemsChange }: TaxInvoiceItemTableProps) {
  const updateItem = useCallback(
    (id: string, field: keyof TaxInvoiceItem, value: string | number) => {
      onItemsChange(
        items.map((item) => {
          if (item.id !== id) return item;

          const updated = { ...item, [field]: value };

          // 자동 계산: 수량, 단가, 과세유형 변경 시
          if (field === 'quantity' || field === 'unitPrice' || field === 'taxType') {
            const qty = field === 'quantity' ? Number(value) : updated.quantity;
            const price = field === 'unitPrice' ? Number(value) : updated.unitPrice;
            const taxType = field === 'taxType' ? (value as 'taxable' | 'taxFree') : updated.taxType;

            updated.supplyAmount = qty * price;
            updated.taxAmount = taxType === 'taxable' ? Math.floor(updated.supplyAmount * 0.1) : 0;
            updated.totalAmount = updated.supplyAmount + updated.taxAmount;
          }

          return updated;
        })
      );
    },
    [items, onItemsChange]
  );

  const addItem = useCallback(() => {
    onItemsChange([...items, createEmptyItem()]);
  }, [items, onItemsChange]);

  const removeItem = useCallback(
    (id: string) => {
      onItemsChange(items.filter((item) => item.id !== id));
    },
    [items, onItemsChange]
  );

  // formatNumber imported from @/lib/utils/amount

  // 합계 계산
  const totals = items.reduce(
    (acc, item) => ({
      supplyAmount: acc.supplyAmount + item.supplyAmount,
      taxAmount: acc.taxAmount + item.taxAmount,
      totalAmount: acc.totalAmount + item.totalAmount,
    }),
    { supplyAmount: 0, taxAmount: 0, totalAmount: 0 }
  );

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium">품목 내역</h4>
        <Button type="button" variant="outline" size="sm" onClick={addItem}>
          <Plus className="h-4 w-4 mr-1" />
          품목 추가
        </Button>
      </div>

      <div className="border rounded-md overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[60px] text-center">월</TableHead>
              <TableHead className="w-[60px] text-center">일</TableHead>
              <TableHead className="min-w-[120px]">품목</TableHead>
              <TableHead className="min-w-[80px]">규격</TableHead>
              <TableHead className="w-[80px] text-right">수량</TableHead>
              <TableHead className="w-[100px] text-right">단가</TableHead>
              <TableHead className="w-[110px] text-right">공급가액</TableHead>
              <TableHead className="w-[100px] text-right">세액</TableHead>
              <TableHead className="w-[110px] text-right">합계</TableHead>
              <TableHead className="w-[80px] text-center">과세</TableHead>
              <TableHead className="w-[50px]" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((item) => (
              <TableRow key={item.id}>
                <TableCell className="p-1">
                  <Input
                    value={item.month}
                    onChange={(e) => updateItem(item.id, 'month', e.target.value)}
                    placeholder="MM"
                    className="h-8 text-center text-sm"
                    maxLength={2}
                  />
                </TableCell>
                <TableCell className="p-1">
                  <Input
                    value={item.day}
                    onChange={(e) => updateItem(item.id, 'day', e.target.value)}
                    placeholder="DD"
                    className="h-8 text-center text-sm"
                    maxLength={2}
                  />
                </TableCell>
                <TableCell className="p-1">
                  <Input
                    value={item.itemName}
                    onChange={(e) => updateItem(item.id, 'itemName', e.target.value)}
                    placeholder="품목명"
                    className="h-8 text-sm"
                  />
                </TableCell>
                <TableCell className="p-1">
                  <Input
                    value={item.specification}
                    onChange={(e) => updateItem(item.id, 'specification', e.target.value)}
                    placeholder="규격"
                    className="h-8 text-sm"
                  />
                </TableCell>
                <TableCell className="p-1">
                  <Input
                    type="number"
                    value={item.quantity || ''}
                    onChange={(e) => updateItem(item.id, 'quantity', Number(e.target.value) || 0)}
                    placeholder="0"
                    className="h-8 text-sm text-right"
                    min={0}
                  />
                </TableCell>
                <TableCell className="p-1">
                  <CurrencyInput
                    value={item.unitPrice || 0}
                    onChange={(v) => updateItem(item.id, 'unitPrice', v ?? 0)}
                    className="h-8 text-sm"
                    showCurrency={false}
                  />
                </TableCell>
                <TableCell className="p-1 text-right text-sm font-medium">
                  {formatNumber(item.supplyAmount)}
                </TableCell>
                <TableCell className="p-1 text-right text-sm">
                  {formatNumber(item.taxAmount)}
                </TableCell>
                <TableCell className="p-1 text-right text-sm font-medium">
                  {formatNumber(item.totalAmount)}
                </TableCell>
                <TableCell className="p-1">
                  <Select
                    value={item.taxType}
                    onValueChange={(v) => updateItem(item.id, 'taxType', v)}
                  >
                    <SelectTrigger className="h-8 text-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {TAX_TYPE_OPTIONS.map((opt) => (
                        <SelectItem key={opt.value} value={opt.value}>
                          {opt.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </TableCell>
                <TableCell className="p-1">
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => removeItem(item.id)}
                    className="h-8 w-8 p-0 text-muted-foreground hover:text-red-500"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </TableCell>
              </TableRow>
            ))}

            {items.length === 0 && (
              <TableRow>
                <TableCell colSpan={11} className="text-center text-muted-foreground py-8">
                  품목을 추가하세요.
                </TableCell>
              </TableRow>
            )}

            {/* 합계 행 */}
            {items.length > 0 && (
              <TableRow className="bg-muted/50 font-medium">
                <TableCell colSpan={6} className="text-right text-sm pr-4">
                  합계
                </TableCell>
                <TableCell className="text-right text-sm p-1">
                  {formatNumber(totals.supplyAmount)}
                </TableCell>
                <TableCell className="text-right text-sm p-1">
                  {formatNumber(totals.taxAmount)}
                </TableCell>
                <TableCell className="text-right text-sm p-1">
                  {formatNumber(totals.totalAmount)}
                </TableCell>
                <TableCell colSpan={2} />
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
