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

// bom/bomList.jsp 대응 - BOM 관리
export default function BomPage() {
  const [productName, setProductName] = useState("");
  const [partNo, setPartNo] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "제품명", field: "PRODUCT_NAME", width: 180, hozAlign: "left",
      cellClick: (row) => window.open(`/product/part-register/form?objId=${row.OBJID}`, "bomDetail", "width=1200,height=900") },
    { title: "제품코드", field: "PRODUCT_CODE", width: 120, hozAlign: "left" },
    { title: "Level", field: "BOM_LEVEL", width: 60, hozAlign: "center" },
    { title: "파트번호", field: "PART_NO", width: 130, hozAlign: "left" },
    { title: "파트명", field: "PART_NAME", width: 180, hozAlign: "left" },
    { title: "규격", field: "SPEC", width: 120, hozAlign: "left" },
    { title: "수량", field: "QTY", width: 70, hozAlign: "right", formatter: "money" },
    { title: "단위", field: "UNIT_NAME", width: 60, hozAlign: "center" },
    { title: "재질", field: "MATERIAL_NAME", width: 100, hozAlign: "left" },
    { title: "비고", field: "REMARK", hozAlign: "left" },
  ];

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

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

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

      <SearchForm onSearch={fetchData}>
        <SearchField label="제품명">
          <Input value={productName} onChange={(e) => setProductName(e.target.value)} className="w-[180px]" />
        </SearchField>
        <SearchField label="파트번호">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[130px]" />
        </SearchField>
      </SearchForm>

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