"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 FundPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [month, setMonth] = useState("");
  const [partnerObjid, setPartnerObjid] = useState("");
  const [paymentStatus, setPaymentStatus] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "공급업체", field: "PARTNER_NAME", width: 180, hozAlign: "left" },
    { title: "발주금액", field: "ORDER_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "입고금액", field: "DELIVERY_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "지급예정금액", field: "PAYMENT_PLAN_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "지급완료금액", field: "PAYMENT_DONE_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "미지급금액", field: "UNPAID_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "지급예정일", field: "PAYMENT_PLAN_DATE", width: 100, hozAlign: "center" },
    { title: "지급상태", field: "PAYMENT_STATUS_NAME", width: 90, hozAlign: "center" },
    { title: "비고", field: "REMARK", width: 200, hozAlign: "left" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/inventory/fund", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        month,
        partner_objid: partnerObjid,
        payment_status: paymentStatus,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, month, partnerObjid, paymentStatus]);

  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="월">
          <select value={month} onChange={(e) => setMonth(e.target.value)}
            className="h-9 w-[80px] rounded border border-gray-300 bg-white px-3 text-sm">
            <option value="">전체</option>
            {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
              <option key={m} value={String(m).padStart(2, "0")}>{m}월</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="공급업체">
          <CodeSelect codeId="PARTNER" value={partnerObjid} onChange={setPartnerObjid} className="w-[160px]" />
        </SearchField>
        <SearchField label="지급상태">
          <CodeSelect codeId="PAYMENT_STATUS" value={paymentStatus} onChange={setPaymentStatus} className="w-[130px]" />
        </SearchField>
      </SearchForm>

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

        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
