"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";
import Swal from "sweetalert2";

// 자재관리 > 현황
export default function InventoryStatusPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [locationCd, setLocationCd] = useState("");
  const [partTypeCd, setPartTypeCd] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 130, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_NAME", width: 120, hozAlign: "center" },
    { title: "부품구분", field: "PART_TYPE_NAME", width: 90, hozAlign: "center" },
    { title: "위치", field: "LOCATION_NAME", width: 100, hozAlign: "center" },
    { title: "총보유수량", field: "TOTAL_QTY", width: 100, hozAlign: "right", formatter: "money" },
    { title: "불출수량", field: "REQUEST_QTY", width: 90, hozAlign: "right", formatter: "money" },
    { title: "잔여수량", field: "REMAIN_QTY", width: 90, hozAlign: "right", formatter: "money" },
    { title: "입고수량", field: "DELIVERY_QTY", width: 90, hozAlign: "right", formatter: "money" },
    { title: "이동수량", field: "MOVE_QTY", width: 90, hozAlign: "right", formatter: "money" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/inventory/status", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        project_no: projectNo,
        location_cd: locationCd,
        part_type_cd: partTypeCd,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, projectNo, locationCd, partTypeCd]);

  const handleExcelDownload = () => {
    Swal.fire("알림", "Excel 다운로드 기능은 준비 중입니다.", "info");
  };

  // 페이지 진입 시 자동 로드
  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" variant="secondary" onClick={fetchData}>조회</Button>
          <Button size="sm" variant="secondary" onClick={handleExcelDownload}>Excel Download</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">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} placeholder="프로젝트번호" className="w-[150px]" />
        </SearchField>
        <SearchField label="위치">
          <CodeSelect codeId="LOCATION" value={locationCd} onChange={setLocationCd} className="w-[130px]" />
        </SearchField>
        <SearchField label="부품구분">
          <CodeSelect codeId="PART_TYPE" value={partTypeCd} onChange={setPartTypeCd} className="w-[130px]" />
        </SearchField>
      </SearchForm>

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

      />
    </div>
  );
}
