"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/partmgmtList.jsp 대응 - 부품관리(PART)
export default function PartMgmtPage() {
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [partType, setPartType] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "파트번호", field: "PART_NO", width: 150, hozAlign: "left",
      cellClick: (row) => openPartDetail(String(row.OBJID)) },
    { title: "파트명", field: "PART_NAME", width: 200, hozAlign: "left" },
    { title: "파트유형", field: "PART_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "규격", field: "SPEC", width: 130, hozAlign: "left" },
    { title: "재질", field: "MATERIAL_NAME", width: 100, hozAlign: "left" },
    { title: "UNIT", field: "UNIT_NAME", width: 70, hozAlign: "center" },
    { title: "중량", field: "WEIGHT", width: 80, hozAlign: "right" },
    { title: "업체", field: "MAKER", width: 120, hozAlign: "left" },
    { title: "등록자", field: "WRITER_NAME", width: 90, hozAlign: "center" },
    { title: "등록일", field: "REGDATE", width: 100, hozAlign: "center" },
    { title: "2D", field: "DRAWING_2D_CNT", width: 40, hozAlign: "center" },
    { title: "3D", field: "DRAWING_3D_CNT", width: 40, hozAlign: "center" },
  ];

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

  const openPartDetail = (objId: string) => {
    window.open(`/product-mgmt/form?objId=${objId}`, "partDetail", "width=1100,height=800");
  };

  // 페이지 진입 시 자동 로드
  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-mgmt/form", "partForm", "width=1100,height=800")}>등록</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-[150px]" />
        </SearchField>
        <SearchField label="파트명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="파트유형">
          <CodeSelect codeId="0000062" value={partType} onChange={setPartType} placeholder="전체" className="w-[130px]" />
        </SearchField>
      </SearchForm>

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