/**
 * 驗收流程管理 Hook
 */

import { useState, useEffect } from "react";
import type { PurchaseOrder, InspectionItem } from "../types/purchase-order";

interface UseInspectionProps {
  order?: PurchaseOrder;
}

export function useInspection({ order }: UseInspectionProps) {
  const [inspectionItems, setInspectionItems] = useState<InspectionItem[]>([]);

  // 極速驗收模式：預設所有實際到貨數量 = 應到貨數量
  useEffect(() => {
    if (order) {
      setInspectionItems(
        order.items.map((item) => ({
          ...item,
          receivedQuantity: item.quantity,
          damagedQuantity: 0,
          shortageQuantity: 0,
          issueType: "none",
        }))
      );
    }
  }, [order]);

  // 更新實際收貨數量
  const updateReceivedQuantity = (index: number, value: number) => {
    const newItems = [...inspectionItems];
    const item = newItems[index];
    const expectedQty = item.quantity;

    item.receivedQuantity = value;

    // 自動計算短缺數量
    item.shortageQuantity = expectedQty - value;

    // 判斷是否有異常（實際收貨 < 應到貨）
    item.issueType = value < expectedQty ? "shortage" : "none";

    setInspectionItems(newItems);
  };

  // 更新異常說明
  const updateIssueNote = (index: number, note: string) => {
    const newItems = [...inspectionItems];
    newItems[index].issueNote = note;
    setInspectionItems(newItems);
  };

  // 計算統計資訊
  const statistics = {
    hasIssues: inspectionItems.some((item) => item.issueType !== "none"),
    issueItems: inspectionItems.filter((item) => item.issueType !== "none"),
    damagedItems: 0, // 不再追蹤損壞數量
    shortageItems: inspectionItems.filter((item) => item.shortageQuantity > 0).length,
    totalExpectedAmount: order?.totalAmount || 0,
    totalReceivedAmount: inspectionItems.reduce(
      (sum, item) => sum + item.receivedQuantity * item.unitPrice,
      0
    ),
  };

  return {
    inspectionItems,
    statistics,
    updateReceivedQuantity,
    updateIssueNote,
  };
}