"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";

// quality/qualityList.jsp 대응 - 품질관리
export default function QualityPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [partNo, setPartNo] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120 },
    { title: "파트번호", field: "PART_NO", width: 130, hozAlign: "left",
      cellClick: (row) => window.open(`/production/inspection/form?objId=${row.OBJID}`, "qualityDetail", "width=1000,height=700") },
    { title: "파트명", field: "PART_NAME", width: 180, hozAlign: "left" },
    { title: "검사유형", field: "TEST_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "검사결과", field: "TEST_RESULT_NAME", width: 100, hozAlign: "center" },
    { title: "검사일", field: "TEST_DATE", width: 100, hozAlign: "center" },
    { title: "검사자", field: "TESTER_NAME", width: 90, hozAlign: "center" },
    { title: "판정", field: "JUDGMENT", width: 80, hozAlign: "center" },
  ];

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

  // 페이지 진입 시 자동 로드
  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={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[130px]" />
        </SearchField>
      </SearchForm>
      <DataGrid columns={columns} data={data} />
    </div>
  );
}
