"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 { ApprovalButton } from "@/components/approval/ApprovalButton";

// fundMgmt/fundExpenseFormList.jsp 대응 - 경비신청서관리
export default function FundExpenseFormPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [writerName, setWriterName] = useState("");
  const [statusCode, setStatusCode] = useState("");
  const [expenseDateFrom, setExpenseDateFrom] = useState("");
  const [expenseDateTo, setExpenseDateTo] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "신청번호", field: "EXPENSE_FORM_NO", width: 140, hozAlign: "left",
      cellClick: (row) => window.open(`/fund/expense-form/form?objId=${row.OBJID}`, "expenseFormDetail", "width=1000,height=700") },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "left" },
    { title: "프로젝트명", field: "PROJECT_NAME", width: 200, hozAlign: "left" },
    { title: "신청자", field: "WRITER_NAME", width: 80, hozAlign: "center" },
    { title: "신청일", field: "EXPENSE_DATE", width: 100, hozAlign: "center" },
    { title: "경비구분", field: "EXPENSE_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "신청금액", field: "EXPENSE_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "사용처", field: "EXPENSE_PLACE", width: 150, hozAlign: "left" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/fund/expense-form", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        writer_name: writerName,
        status_code: statusCode,
        expense_date_from: expenseDateFrom,
        expense_date_to: expenseDateTo,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, writerName, statusCode, expenseDateFrom, expenseDateTo]);

  // 페이지 진입 시 자동 로드
  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("/fund/expense-form/form", "expenseFormNew", "width=1000,height=700")}>등록</Button>
          <ApprovalButton
            objIds={selectedRows.map((r) => String(r.OBJID))}
            targetType="EXPENSE_APPLY"
            title={`경비 결재 요청 (${selectedRows.length}건)`}
            description={selectedRows.map((r) => `${r.EXPENSE_ID} - ${r.BUS_TITLE}`).join("\n")}
            onSuccess={fetchData}
            disabled={selectedRows.length === 0}
          />
          <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={writerName} onChange={(e) => setWriterName(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="상태">
          <CodeSelect codeId="EXPENSE_STATUS" value={statusCode} onChange={setStatusCode} className="w-[120px]" />
        </SearchField>
        <SearchField label="신청일(From)">
          <Input type="date" value={expenseDateFrom} onChange={(e) => setExpenseDateFrom(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="신청일(To)">
          <Input type="date" value={expenseDateTo} onChange={(e) => setExpenseDateTo(e.target.value)} className="w-[140px]" />
        </SearchField>
      </SearchForm>

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