'use client';

/**
 * 공통 품목 테이블 컴포넌트
 * 매출/매입/세금계산서 등의 품목 입력 테이블에서 공유
 *
 * 기본 컬럼: #, 품목명, 수량, 단가, 공급가액, 부가세, 적요, 삭제
 */

import React from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { QuantityInput } from '@/components/ui/quantity-input';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { formatNumber as formatAmount } from '@/lib/utils/amount';
import type { LineItemTotals } from './types';

export interface LineItemsTableProps<T extends { id: string }> {
  items: T[];
  /** 품목명 가져오기 */
  getItemName: (item: T) => string;
  /** 수량 가져오기 */
  getQuantity: (item: T) => number;
  /** 단가 가져오기 */
  getUnitPrice: (item: T) => number;
  /** 공급가액 가져오기 */
  getSupplyAmount: (item: T) => number;
  /** 부가세 가져오기 */
  getVat: (item: T) => number;
  /** 적요 가져오기 */
  getNote?: (item: T) => string;
  /** 필드 변경 핸들러 */
  onItemChange: (index: number, field: string, value: string | number) => void;
  /** 행 추가 */
  onAddItem: () => void;
  /** 행 삭제 */
  onRemoveItem: (index: number) => void;
  /** 합계 */
  totals: LineItemTotals;
  /** view 모드 여부 */
  isViewMode?: boolean;
  /** 최소 유지 행 수 (삭제 버튼 표시 기준, 기본 1) */
  minItems?: number;
  /** 추가 버튼 라벨 */
  addButtonLabel?: string;
  /** 적요 컬럼 표시 여부 (기본 true) */
  showNote?: boolean;
  /** 테이블 앞뒤에 추가 컬럼 렌더링 */
  renderExtraHeaders?: () => React.ReactNode;
  renderExtraCells?: (item: T, index: number) => React.ReactNode;
  renderExtraTotalCells?: () => React.ReactNode;
}

export function LineItemsTable<T extends { id: string }>({
  items,
  getItemName,
  getQuantity,
  getUnitPrice,
  getSupplyAmount,
  getVat,
  getNote,
  onItemChange,
  onAddItem,
  onRemoveItem,
  totals,
  isViewMode = false,
  minItems = 1,
  addButtonLabel = '추가',
  showNote = true,
  renderExtraHeaders,
  renderExtraCells,
  renderExtraTotalCells,
}: LineItemsTableProps<T>) {
  const noteColSpan = showNote ? 2 : 1; // 적요+삭제 or 삭제만

  return (
    <>
      <div className="overflow-x-auto">
        <Table className="min-w-[1000px]">
          <TableHeader>
            <TableRow>
              <TableHead className="w-[50px] text-center">#</TableHead>
              <TableHead className="min-w-[200px]">품목명</TableHead>
              <TableHead className="w-[130px] text-right">수량</TableHead>
              <TableHead className="w-[160px] text-right">단가</TableHead>
              <TableHead className="w-[160px] text-right">공급가액</TableHead>
              <TableHead className="w-[140px] text-right">부가세</TableHead>
              {renderExtraHeaders?.()}
              {showNote && <TableHead>적요</TableHead>}
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((item, index) => (
              <TableRow key={item.id}>
                <TableCell className="text-center">{index + 1}</TableCell>
                <TableCell>
                  <Input
                    value={getItemName(item)}
                    onChange={(e) => onItemChange(index, 'itemName', e.target.value)}
                    placeholder="품목명"
                    disabled={isViewMode}
                  />
                </TableCell>
                <TableCell className="text-right">
                  <QuantityInput
                    value={getQuantity(item)}
                    onChange={(value) => onItemChange(index, 'quantity', value ?? 0)}
                    disabled={isViewMode}
                    min={1}
                  />
                </TableCell>
                <TableCell className="text-right">
                  <CurrencyInput
                    value={getUnitPrice(item)}
                    onChange={(value) => onItemChange(index, 'unitPrice', value ?? 0)}
                    disabled={isViewMode}
                  />
                </TableCell>
                <TableCell className="text-right font-medium">
                  {formatAmount(getSupplyAmount(item))}
                </TableCell>
                <TableCell className="text-right">
                  {formatAmount(getVat(item))}
                </TableCell>
                {renderExtraCells?.(item, index)}
                {showNote && (
                  <TableCell>
                    <Input
                      value={getNote?.(item) ?? ''}
                      onChange={(e) => onItemChange(index, 'note', e.target.value)}
                      placeholder="적요"
                      disabled={isViewMode}
                    />
                  </TableCell>
                )}
                <TableCell>
                  {!isViewMode && items.length > minItems && (
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-red-600 hover:text-red-700"
                      onClick={() => onRemoveItem(index)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  )}
                </TableCell>
              </TableRow>
            ))}
            {/* 합계 행 */}
            <TableRow className="bg-gray-50 font-medium">
              <TableCell colSpan={4} className="text-right">
                합계
              </TableCell>
              <TableCell className="text-right">
                {formatAmount(totals.supplyAmount)}
              </TableCell>
              <TableCell className="text-right">
                {formatAmount(totals.vat)}
              </TableCell>
              {renderExtraTotalCells?.()}
              <TableCell colSpan={noteColSpan}></TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </div>

      {/* 품목 추가 버튼 */}
      {!isViewMode && (
        <div className="mt-4">
          <Button variant="outline" onClick={onAddItem}>
            <Plus className="h-4 w-4 mr-2" />
            {addButtonLabel}
          </Button>
        </div>
      )}
    </>
  );
}
