/**
 * 품목 리스트 관리 훅
 * add / remove / update + 자동 계산 로직을 공통화
 */

import { useCallback, useMemo } from 'react';
import { recalculate } from './calculations';
import type { LineItemTotals } from './types';

interface UseLineItemsOptions<T> {
  items: T[];
  setItems: React.Dispatch<React.SetStateAction<T[]>>;
  createEmptyItem: () => T;
  /** 공급가액 필드 키 (기본 'supplyAmount') */
  supplyKey?: keyof T;
  /** 부가세 필드 키 (기본 'vat') */
  vatKey?: keyof T;
  /** 세율 (기본 0.1) */
  taxRate?: number;
  /** 최소 유지 행 수 (기본 1) */
  minItems?: number;
}

export function useLineItems<T extends { id: string; quantity: number; unitPrice: number }>({
  items,
  setItems,
  createEmptyItem,
  supplyKey = 'supplyAmount' as keyof T,
  vatKey = 'vat' as keyof T,
  taxRate = 0.1,
  minItems = 1,
}: UseLineItemsOptions<T>) {
  const handleItemChange = useCallback(
    (index: number, field: string, value: string | number) => {
      setItems((prev) => {
        const newItems = [...prev];
        const item = { ...newItems[index] };

        if (field === 'quantity' || field === 'unitPrice') {
          const numValue = typeof value === 'string' ? parseFloat(value) || 0 : value;
          (item as any)[field] = numValue;
          const qty = field === 'quantity' ? numValue : item.quantity;
          const price = field === 'unitPrice' ? numValue : item.unitPrice;
          const calc = recalculate(qty, price, taxRate);
          (item as any)[supplyKey] = calc.supplyAmount;
          (item as any)[vatKey] = calc.vat;
        } else {
          (item as any)[field] = value;
        }

        newItems[index] = item;
        return newItems;
      });
    },
    [setItems, supplyKey, vatKey, taxRate],
  );

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

  const handleRemoveItem = useCallback(
    (index: number) => {
      setItems((prev) => {
        if (prev.length <= minItems) return prev;
        return prev.filter((_, i) => i !== index);
      });
    },
    [setItems, minItems],
  );

  const totals: LineItemTotals = useMemo(() => {
    const totalSupply = items.reduce((sum, item) => sum + ((item as any)[supplyKey] ?? 0), 0);
    const totalVat = items.reduce((sum, item) => sum + ((item as any)[vatKey] ?? 0), 0);
    return {
      supplyAmount: totalSupply,
      vat: totalVat,
      total: totalSupply + totalVat,
    };
  }, [items, supplyKey, vatKey]);

  return {
    handleItemChange,
    handleAddItem,
    handleRemoveItem,
    totals,
  };
}
