'use client';

/**
 * 부적합관리 - 자재 상세 테이블
 *
 * 행 추가/삭제, 수량×단가=금액 자동계산
 * 합계(material_cost) 변경 시 부모에 콜백
 */

import { useCallback } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { NumberInput } from '@/components/ui/number-input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { formatAmount } from '@/lib/utils/amount';
import { type NonconformingReportItem, EMPTY_ITEM } from './types';

interface NonconformingItemTableProps {
  items: NonconformingReportItem[];
  onChange: (items: NonconformingReportItem[]) => void;
  disabled?: boolean;
}

export function NonconformingItemTable({
  items,
  onChange,
  disabled = false,
}: NonconformingItemTableProps) {

  const handleAddRow = useCallback(() => {
    onChange([...items, { ...EMPTY_ITEM, sort_order: items.length }]);
  }, [items, onChange]);

  const handleRemoveRow = useCallback(
    (index: number) => {
      const next = items.filter((_, i) => i !== index).map((item, i) => ({ ...item, sort_order: i }));
      onChange(next);
    },
    [items, onChange]
  );

  const handleFieldChange = useCallback(
    (index: number, field: keyof NonconformingReportItem, value: string | number) => {
      const next = items.map((item, i) => {
        if (i !== index) return item;
        const updated = { ...item, [field]: value };
        // 수량 또는 단가 변경 시 금액 자동 계산
        if (field === 'quantity' || field === 'unit_price') {
          const qty = field === 'quantity' ? Number(value) : Number(updated.quantity);
          const price = field === 'unit_price' ? Number(value) : Number(updated.unit_price);
          updated.amount = qty * price;
        }
        return updated;
      });
      onChange(next);
    },
    [items, onChange]
  );

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

  return (
    <div className="space-y-3">
      <div className="border rounded-md overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="text-center w-[50px]">No</TableHead>
              <TableHead className="min-w-[150px]">품목명</TableHead>
              <TableHead className="min-w-[120px]">규격</TableHead>
              <TableHead className="text-right w-[100px]">수량</TableHead>
              <TableHead className="text-right w-[110px]">단가</TableHead>
              <TableHead className="text-right w-[110px]">금액</TableHead>
              <TableHead className="min-w-[100px]">비고</TableHead>
              {!disabled && <TableHead className="text-center w-[50px]" />}
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={disabled ? 7 : 8} className="text-center text-muted-foreground py-8">
                  자재 내역이 없습니다. {!disabled && '아래 버튼으로 행을 추가하세요.'}
                </TableCell>
              </TableRow>
            ) : (
              items.map((item, index) => (
                <TableRow key={index}>
                  <TableCell className="text-center text-muted-foreground">{index + 1}</TableCell>
                  <TableCell>
                    {disabled ? (
                      <span>{item.item_name || '-'}</span>
                    ) : (
                      <Input
                        value={item.item_name}
                        onChange={(e) => handleFieldChange(index, 'item_name', e.target.value)}
                        placeholder="품목명"
                        className="h-8"
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    {disabled ? (
                      <span>{item.specification || '-'}</span>
                    ) : (
                      <Input
                        value={item.specification}
                        onChange={(e) => handleFieldChange(index, 'specification', e.target.value)}
                        placeholder="규격"
                        className="h-8"
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    {disabled ? (
                      <span className="block text-right">{item.quantity}</span>
                    ) : (
                      <NumberInput
                        value={item.quantity}
                        onChange={(val) => handleFieldChange(index, 'quantity', val ?? 0)}
                        className="h-8 text-right"
                        min={0}
                        allowDecimal
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    {disabled ? (
                      <span className="block text-right">{formatAmount(item.unit_price)}</span>
                    ) : (
                      <NumberInput
                        value={item.unit_price}
                        onChange={(val) => handleFieldChange(index, 'unit_price', val ?? 0)}
                        className="h-8 text-right"
                        min={0}
                        useComma
                      />
                    )}
                  </TableCell>
                  <TableCell className="text-right font-medium">
                    {formatAmount(item.amount)}
                  </TableCell>
                  <TableCell>
                    {disabled ? (
                      <span>{item.remarks || '-'}</span>
                    ) : (
                      <Input
                        value={item.remarks}
                        onChange={(e) => handleFieldChange(index, 'remarks', e.target.value)}
                        placeholder="비고"
                        className="h-8"
                      />
                    )}
                  </TableCell>
                  {!disabled && (
                    <TableCell className="text-center">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 text-red-500 hover:text-red-700"
                        onClick={() => handleRemoveRow(index)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
            {/* 합계 행 */}
            {items.length > 0 && (
              <TableRow className="bg-muted/50 font-medium">
                <TableCell colSpan={5} className="text-right">
                  자재비용 합계
                </TableCell>
                <TableCell className="text-right font-bold text-blue-700">
                  {formatAmount(totalAmount)}
                </TableCell>
                <TableCell colSpan={disabled ? 1 : 2} />
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {!disabled && (
        <Button variant="outline" size="sm" onClick={handleAddRow}>
          <Plus className="h-4 w-4 mr-1" />
          행 추가
        </Button>
      )}
    </div>
  );
}
