"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 { CodeSelect } from "@/components/ui/code-select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

// inventoryMngInputList.jsp 대응 - 재고관리(입고)
export default function InventoryPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [spec, setSpec] = useState("");
  const [clsCd, setClsCd] = useState("");
  const [cauCd, setCauCd] = useState("");
  const [location, setLocation] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [totalCount, setTotalCount] = useState(0);

  // inventoryMngInputList.jsp columns 대응
  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 100, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_NAME", hozAlign: "left" },
    { title: "파트번호", field: "PART_NO", width: 130, hozAlign: "left" },
    { title: "파트명", field: "PART_NAME", width: 150, hozAlign: "left" },
    { title: "규격", field: "SPEC", width: 110, hozAlign: "left" },
    { title: "업체", field: "MAKER", width: 100, hozAlign: "left" },
    { title: "재고구분", field: "CLS_CD_NAME", width: 90, hozAlign: "center" },
    { title: "발생사유", field: "CAU_CD_NAME", width: 100, hozAlign: "center" },
    { title: "발생수량", field: "QTY", width: 90, hozAlign: "right", formatter: "money" },
    { title: "위치", field: "LOCATION_NAME", width: 100, hozAlign: "left" },
    { title: "금액(원)", field: "PRICE", width: 100, hozAlign: "right", formatter: "money" },
    { title: "등록일", field: "REG_DATE", width: 90, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 90, hozAlign: "center" },
    { title: "총입고수량", field: "INPUT_QTY", width: 90, hozAlign: "center",
      cellClick: (row) => openHistoryPopup(String(row.OBJID)) },
    { title: "최종입고일", field: "INPUT_DATE", width: 90, hozAlign: "center" },
    { title: "잔여수량", field: "REMAIN_QTY", width: 90, hozAlign: "center",
      cellClick: (row) => openHistoryPopup(String(row.OBJID)) },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/inventory", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year, project_no: projectNo, part_no: partNo, part_name: partName,
        spec, cls_cd: clsCd, cau_cd: cauCd, location,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
      setTotalCount(json.TOTAL_CNT || 0);
    }
  }, [year, projectNo, partNo, partName, spec, clsCd, cauCd, location]);

  const openHistoryPopup = (objId: string) => {
    window.open(`/inventory/history?objId=${objId}`, "inventoryHistory", "width=600,height=500");
  };

  const openInputPopup = () => {
    window.open("/inventory/input-form", "inventoryInput", "width=850,height=330");
  };

  // 페이지 진입 시 자동 로드
  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" onClick={openInputPopup}>입고등록</Button>
          <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"
          >
            <option value="">전체</option>
            {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-[120px]" />
        </SearchField>

        <SearchField label="파트명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[120px]" />
        </SearchField>

        <SearchField label="규격">
          <Input value={spec} onChange={(e) => setSpec(e.target.value)} className="w-[100px]" />
        </SearchField>

        <SearchField label="재고구분">
          <CodeSelect codeId="0001576" value={clsCd} onChange={setClsCd} placeholder="전체" className="w-[120px]" />
        </SearchField>

        <SearchField label="위치">
          <CodeSelect codeId="0000262" value={location} onChange={setLocation} placeholder="전체" className="w-[120px]" />
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox

      />
    </div>
  );
}
