"use client";

import { useState, useCallback, useEffect } from "react";
import Swal from "sweetalert2";
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";

// costMgmt/expenseDashBoard.jsp 대응 - 경비관리
export default function CostExpensePage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [pmUserId, setPmUserId] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selected, setSelected] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "left", frozen: true },
    {
      title: "프로젝트정보",
      columns: [
        { title: "고객사", field: "CUSTOMER_NAME", width: 150, hozAlign: "left" },
        { title: "프로젝트명", field: "PROJECT_NAME", width: 200, hozAlign: "left" },
        { title: "요청납기일", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
        { title: "셋업지", field: "SETUP", width: 100, hozAlign: "left" },
        { title: "PM", field: "PM_USER_NAME", width: 80, hozAlign: "center" },
      ],
    },
    {
      title: "경비현황",
      columns: [
        { title: "목표가", field: "EXPENSE_COST_GOAL", width: 120, hozAlign: "right", formatter: "money" },
        { title: "발생경비", field: "TOTAL_SETTLE_AMOUNT", width: 130, hozAlign: "right", formatter: "money" },
        { title: "투입율(%)", field: "INPUT_RATE", width: 90, hozAlign: "right" },
        { title: "조립", field: "SETTLE_AMOUNT_ASSEMBLE", width: 120, hozAlign: "right", formatter: "money" },
        { title: "셋업", field: "SETTLE_AMOUNT_SETUP", width: 120, hozAlign: "right", formatter: "money" },
        { title: "외주(Turn-key)", field: "SETTLE_AMOUNT_CS", width: 130, hozAlign: "right", formatter: "money" },
      ],
    },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/cost/expense", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year, project_no: projectNo, customer_objid: customerObjid, pm_user_id: pmUserId,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, projectNo, customerObjid, pmUserId]);

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

  useEffect(() => {
    (window as unknown as { fn_search?: () => void }).fn_search = fetchData;
    return () => { delete (window as unknown as { fn_search?: () => void }).fn_search; };
  }, [fetchData]);

  const openExpenseApply = () => {
    const contractObjid = selected.length === 1 ? String(selected[0].OBJID || "") : "";
    if (selected.length > 1) {
      Swal.fire({ icon: "warning", title: "한번에 1개의 프로젝트만 선택 가능합니다." });
      return;
    }
    const w = 900, h = 600;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/cost/expense/apply${contractObjid ? `?contractObjid=${encodeURIComponent(contractObjid)}` : ""}`,
      "expenseApply",
      `width=${w},height=${h},left=${left},top=${top},scrollbars=yes,resizable=yes`
    );
  };

  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={openExpenseApply}>경비신청</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={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="고객사">
          <CodeSelect codeId="CUSTOMER" value={customerObjid} onChange={setCustomerObjid} className="w-[160px]" />
        </SearchField>
        <SearchField label="PM">
          <CodeSelect codeId="PM_USER" value={pmUserId} onChange={setPmUserId} className="w-[130px]" />
        </SearchField>
      </SearchForm>

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

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