"use client";

import { useState, useCallback, useEffect } from "react";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { CodeSelect } from "@/components/ui/code-select";

// scm/scmQualityList.jsp 대응 - 공급업체품질관리
export default function ScmQualityPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [supplierName, setSupplierName] = useState("");
  const [evaluationPeriod, setEvaluationPeriod] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "공급업체", field: "SUPPLIER_NAME", width: 150, hozAlign: "left" },
    { title: "평가기간", field: "EVALUATION_PERIOD", width: 100, hozAlign: "center" },
    { title: "납기준수율%", field: "DELIVERY_RATE", width: 100, hozAlign: "right" },
    { title: "품질점수", field: "QUALITY_SCORE", width: 80, hozAlign: "right" },
    { title: "불량율%", field: "DEFECT_RATE", width: 80, hozAlign: "right" },
    { title: "납품건수", field: "DELIVERY_CNT", width: 80, hozAlign: "right" },
    { title: "불량건수", field: "DEFECT_CNT", width: 80, hozAlign: "right" },
    { title: "종합등급", field: "TOTAL_GRADE", width: 80, hozAlign: "center" },
    { title: "평가일", field: "EVALUATION_DATE", width: 100, hozAlign: "center" },
    { title: "평가자", field: "EVALUATOR_NAME", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/scm/quality", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        supplier_name: supplierName,
        evaluation_period: evaluationPeriod,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, supplierName, evaluationPeriod]);

  // 페이지 진입 시 자동 로드
  useEffect(() => { fetchData(); }, [fetchData]);

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">공급업체품질관리</h2>
        <div className="flex gap-2">
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="년도">
          <select value={year} onChange={(e) => setYear(e.target.value)}
            className="h-9 w-[100px] rounded border border-gray-300 bg-white px-3 text-sm">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="공급업체">
          <Input value={supplierName} onChange={(e) => setSupplierName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="평가기간">
          <CodeSelect codeId="EVALUATION_PERIOD" value={evaluationPeriod} onChange={setEvaluationPeriod} className="w-[120px]" />
        </SearchField>
      </SearchForm>

      <DataGrid columns={columns} data={data} />
    </div>
  );
}
