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

// partMgmt/partRegisterList.jsp 대응 - Part 등록
export default function PartRegisterPage() {
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [spec, setSpec] = useState("");
  const [maker, setMaker] = useState("");
  const [categoryCode, setCategoryCode] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "파트번호", field: "PART_NO", width: 140, hozAlign: "left",
      cellClick: (row) => window.open(`/product/part-register/form?objId=${row.OBJID}`, "partDetail", "width=900,height=600") },
    { title: "파트명", field: "PART_NAME", width: 180, hozAlign: "left" },
    { title: "규격", field: "SPEC", width: 150, hozAlign: "left" },
    { title: "단위", field: "UNIT_NAME", width: 60, hozAlign: "center" },
    { title: "카테고리", field: "CATEGORY_NAME", width: 100, hozAlign: "center" },
    { title: "제조사", field: "MAKER", width: 120, hozAlign: "left" },
    { title: "단가", field: "UNIT_PRICE", width: 100, hozAlign: "right", formatter: "money" },
    { title: "등록일", field: "REG_DATE", width: 100, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 80, hozAlign: "center" },
  ];

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

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

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">Part 등록</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={() => window.open("/product/part-register/form", "partForm", "width=900,height=600")}>등록</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="파트번호">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="파트명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="규격">
          <Input value={spec} onChange={(e) => setSpec(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="제조사">
          <Input value={maker} onChange={(e) => setMaker(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="카테고리">
          <CodeSelect codeId="PART_CATEGORY" value={categoryCode} onChange={setCategoryCode} className="w-[130px]" />
        </SearchField>
      </SearchForm>

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