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

// scm/scmPaymentList.jsp 대응 - 자금지급관리
export default function ScmPaymentPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [supplierName, setSupplierName] = useState("");
  const [paymentDateFrom, setPaymentDateFrom] = useState("");
  const [paymentDateTo, setPaymentDateTo] = useState("");
  const [statusCode, setStatusCode] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "지급번호", field: "PAYMENT_NO", width: 140, hozAlign: "left",
      cellClick: (row) => window.open(`/scm/payment/form?objId=${row.OBJID}`, "paymentDetail", "width=1000,height=700") },
    { title: "공급업체", field: "SUPPLIER_NAME", width: 150, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "left" },
    { title: "지급일", field: "PAYMENT_DATE", width: 100, hozAlign: "center" },
    { title: "지급금액", field: "PAYMENT_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "지급구분", field: "PAYMENT_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "계좌번호", field: "ACCOUNT_NO", width: 150, hozAlign: "left" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/scm/payment", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        supplier_name: supplierName,
        payment_date_from: paymentDateFrom,
        payment_date_to: paymentDateTo,
        status_code: statusCode,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, supplierName, paymentDateFrom, paymentDateTo, statusCode]);

  // 페이지 진입 시 자동 로드
  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={() => window.open("/scm/payment/form", "paymentForm", "width=1000,height=700")}>등록</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">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="공급업체">
          <Input value={supplierName} onChange={(e) => setSupplierName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="지급일(From)">
          <Input type="date" value={paymentDateFrom} onChange={(e) => setPaymentDateFrom(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="지급일(To)">
          <Input type="date" value={paymentDateTo} onChange={(e) => setPaymentDateTo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="상태">
          <CodeSelect codeId="PAYMENT_STATUS" value={statusCode} onChange={setStatusCode} className="w-[120px]" />
        </SearchField>
      </SearchForm>

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