"use client";

import { useState, useEffect, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { Button } from "@/components/ui/button";

// 재고 입출고 이력 팝업
export default function InventoryHistoryPage() {
  const searchParams = useSearchParams();
  const objId = searchParams.get("objId") || "";
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const fetchData = useCallback(async () => {
    if (!objId) return;
    const res = await fetch("/api/inventory/history", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ parent_objid: objId }),
    });
    if (res.ok) { const json = await res.json(); setData(json.RESULTLIST || []); }
  }, [objId]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const columns: GridColumn[] = [
    { title: "유형", field: "TYPE", width: 80, hozAlign: "center" },
    { title: "수량", field: "QTY", width: 100, hozAlign: "right", formatter: "money" },
    { title: "일자", field: "HIST_DATE", width: 110, hozAlign: "center" },
    { title: "위치", field: "LOCATION_NAME", width: 100, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 90, hozAlign: "center" },
    { title: "비고", field: "REMARK", hozAlign: "left" },
  ];

  return (
    <div className="p-4">
      <h2 className="text-lg font-bold text-gray-800 mb-3">재고 입출고 이력</h2>
      <DataGrid columns={columns} data={data} />
      <div className="flex justify-end mt-3">
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}
