"use client";

/**
 * 반제품검사 관리 — wace_plm 의 semiProductInspectionList.jsp 1:1 이식.
 * 필터 8종 (2행), 그리드 14컬럼 (재생수량/최종양품 자동산정).
 * 마스터 행은 data_type='GOOD' 이고, 동일 inspection_group_id 의 'DEFECT' 행을 SUM.
 */
import React, { useCallback, useEffect, useState } from "react";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { PageHeader } from "@/components/common/PageHeader";
import { CompactFilterBar, CompactFilterField, CompactDateRange } from "@/components/common/CompactFilterBar";
import { qualityApi, SemiProductInspectionRow } from "@/lib/api/quality";
import { exportToExcel } from "@/lib/utils/excelExport";

// wace_plm semiProductInspectionList.jsp 그리드 1:1
const GRID_COLUMNS: DataGridColumn[] = [
  { key: "inspection_date", label: "검사일",         width: "w-[140px]", align: "center", frozen: true },
  { key: "writer_name",     label: "검사자",         width: "w-[110px]", align: "center" },
  { key: "product_type",    label: "제품구분",       width: "w-[110px]", align: "center" },
  { key: "model_name",      label: "품명(모델명)",   width: "w-[150px]" },
  { key: "work_order_no",   label: "작업지시번호",   width: "w-[140px]", align: "center" },
  { key: "part_no",         label: "부품품번",       width: "w-[150px]" },
  { key: "part_name",       label: "부품명",         width: "w-[180px]" },
  { key: "receipt_qty",     label: "입고수량 합계",  width: "w-[120px]", align: "right", formatNumber: true },
  { key: "good_qty",        label: "양품수량 합계",  width: "w-[120px]", align: "right", formatNumber: true },
  { key: "defective_qty",   label: "불량수량 합계",  width: "w-[120px]", align: "right", formatNumber: true },
  { key: "defect_rate",     label: "불량률(%)",      width: "w-[100px]", align: "right" },
  { key: "regeneration_qty",label: "재생수량 합계",  width: "w-[120px]", align: "right", formatNumber: true },
  { key: "final_good_qty",  label: "최종양품수량 합계", width: "w-[140px]", align: "right", formatNumber: true },
];

export default function SemiProductInspectionPage() {
  const { user } = useAuth();
  const [rows, setRows] = useState<SemiProductInspectionRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedId, setSelectedId] = useState<string | null>(null);

  const [search, setSearch] = useState({
    search_model_name: "",
    search_work_order_no: "",
    search_part_no: "",
    search_part_name: "",
    inspection_start_date: "",
    inspection_end_date: "",
    search_writer: "",
    search_defect_type: "",
    search_responsible_dept: "",
  });

  const fetchList = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    try {
      const res = await qualityApi.semiProductInspection(search);
      setRows(res.list.map((r) => ({ ...r, id: r.objid } as any)));
      setSelectedId(null);
    } catch { toast.error("반제품검사 목록 조회 실패"); }
    finally { setLoading(false); }
  }, [user, search]);

  useEffect(() => { fetchList(); }, [fetchList]);

  const handleReset = () => setSearch({
    search_model_name: "", search_work_order_no: "",
    search_part_no: "", search_part_name: "",
    inspection_start_date: "", inspection_end_date: "",
    search_writer: "", search_defect_type: "", search_responsible_dept: "",
  });

  const summary = (() => {
    const fmt = (n: number) => n.toLocaleString();
    return [
      { label: "총 입고수량",     value: fmt(rows.reduce((a, r) => a + Number(r.receipt_qty || 0), 0)) },
      { label: "총 양품수량",     value: fmt(rows.reduce((a, r) => a + Number(r.good_qty || 0), 0)) },
      { label: "총 불량수량",     value: fmt(rows.reduce((a, r) => a + Number(r.defective_qty || 0), 0)) },
      { label: "총 재생수량",     value: fmt(rows.reduce((a, r) => a + Number(r.regeneration_qty || 0), 0)) },
      { label: "총 최종양품수량", value: fmt(rows.reduce((a, r) => a + Number(r.final_good_qty || 0), 0)) },
    ];
  })();

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader
        loading={loading}
        onSearch={fetchList}
        onReset={handleReset}
        actions={
          <Button size="sm" className="h-8 gap-1 text-xs" disabled>
            <Plus className="h-3.5 w-3.5" />반제품검사 등록
          </Button>
        }
      />
      <CompactFilterBar totalText={<>총 {rows.length.toLocaleString()}건</>}>
        <CompactFilterField label="품명(모델명)" width={160}>
          <Input value={search.search_model_name} onChange={(e) => setSearch({ ...search, search_model_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="작업지시번호" width={150}>
          <Input value={search.search_work_order_no} onChange={(e) => setSearch({ ...search, search_work_order_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="부품품번" width={150}>
          <Input value={search.search_part_no} onChange={(e) => setSearch({ ...search, search_part_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="부품명" width={160}>
          <Input value={search.search_part_name} onChange={(e) => setSearch({ ...search, search_part_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="검사일" width={280}>
          <CompactDateRange
            from={search.inspection_start_date} setFrom={(v) => setSearch({ ...search, inspection_start_date: v })}
            to={search.inspection_end_date}     setTo={(v) => setSearch({ ...search, inspection_end_date: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="검사자 ID" width={120}>
          <Input value={search.search_writer} onChange={(e) => setSearch({ ...search, search_writer: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="불량유형 ID" width={130}>
          <Input value={search.search_defect_type} onChange={(e) => setSearch({ ...search, search_defect_type: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="귀책부서 ID" width={130}>
          <Input value={search.search_responsible_dept} onChange={(e) => setSearch({ ...search, search_responsible_dept: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>
      <DataGrid
        gridId="quality-semi-product-inspection"
        columns={GRID_COLUMNS}
        data={rows}
        loading={loading}
        showCheckbox
        checkedIds={selectedId ? [selectedId] : []}
        onCheckedChange={(ids) => setSelectedId(ids.length ? ids[ids.length - 1] : null)}
        selectedId={selectedId}
        onSelect={setSelectedId}
        emptyMessage="조회된 반제품검사 내역이 없습니다."
        summaryStats={summary}
        showColumnSettings
        paginationStyle="range"
        pageSizeOptions={[10, 15, 20, 50, 100]}
        showChart
        onRefresh={fetchList}
        onDownload={() => {
          if (rows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = rows.map((r) => {
            const out: Record<string, any> = {};
            GRID_COLUMNS.forEach((c) => { out[c.label] = (r as any)[c.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "반제품검사관리.xlsx", "반제품검사관리");
        }}
      />
    </div>
  );
}
