"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 { SearchableSelect } from "@/components/ui/searchable-select";
import { numberWithCommas } from "@/lib/utils";
import Swal from "sweetalert2";

type Option = { value: string; label: string };

// 원본: /purchaseOrder/purchaseOrderStatusAmountBySupply.do
// 발주관리 > 업체별_입고요청월 금액현황
export default function AmountStatusPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [partnerObjid, setPartnerObjid] = useState("");
  const [salesMngUserId, setSalesMngUserId] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [sums, setSums] = useState<Record<string, unknown>>({});
  const [loading, setLoading] = useState(false);

  const [supplyOptions, setSupplyOptions] = useState<Option[]>([]);
  const [userOptions, setUserOptions] = useState<Option[]>([]);

  useEffect(() => {
    fetch("/api/admin/supply", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) =>
        setSupplyOptions(
          (d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.SUPPLY_NAME),
          })),
        ),
      )
      .catch(() => {});

    fetch("/api/admin/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) =>
        setUserOptions(
          (d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.USER_ID),
            label: String(r.USER_NAME),
          })),
        ),
      )
      .catch(() => {});
  }, []);

  const columns: GridColumn[] = [
    { title: "공급업체", field: "SUPPLY_NAME", width: 180, hozAlign: "left", frozen: true },
    { title: "1월", field: "M01", width: 110, hozAlign: "right", formatter: "money" },
    { title: "2월", field: "M02", width: 110, hozAlign: "right", formatter: "money" },
    { title: "3월", field: "M03", width: 110, hozAlign: "right", formatter: "money" },
    { title: "4월", field: "M04", width: 110, hozAlign: "right", formatter: "money" },
    { title: "5월", field: "M05", width: 110, hozAlign: "right", formatter: "money" },
    { title: "6월", field: "M06", width: 110, hozAlign: "right", formatter: "money" },
    { title: "7월", field: "M07", width: 110, hozAlign: "right", formatter: "money" },
    { title: "8월", field: "M08", width: 110, hozAlign: "right", formatter: "money" },
    { title: "9월", field: "M09", width: 110, hozAlign: "right", formatter: "money" },
    { title: "10월", field: "M10", width: 110, hozAlign: "right", formatter: "money" },
    { title: "11월", field: "M11", width: 110, hozAlign: "right", formatter: "money" },
    { title: "12월", field: "M12", width: 110, hozAlign: "right", formatter: "money" },
    { title: "합계", field: "TOTAL_SUPPLY_UNIT_PRICE", width: 140, hozAlign: "right", formatter: "money" },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/order/amount-status", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          year,
          project_no: projectNo,
          partner_objid: partnerObjid,
          sales_mng_user_id: salesMngUserId,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
        setSums(json.SUMS || {});
      } else {
        const j = await res.json().catch(() => ({}));
        Swal.fire("오류", j.message || "조회 실패", "error");
      }
    } finally {
      setLoading(false);
    }
  }, [year, projectNo, partnerObjid, salesMngUserId]);

  const handleReset = () => {
    setYear(new Date().getFullYear().toString());
    setProjectNo("");
    setPartnerObjid("");
    setSalesMngUserId("");
  };

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

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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={handleReset}>초기화</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"
          >
            <option value="">전체</option>
            {Array.from({ length: 6 }, (_, 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-[180px]"
          />
        </SearchField>
        <SearchField label="공급업체">
          <SearchableSelect
            options={supplyOptions}
            value={partnerObjid}
            onChange={setPartnerObjid}
            className="w-[180px]"
          />
        </SearchField>
        <SearchField label="구매담당">
          <SearchableSelect
            options={userOptions}
            value={salesMngUserId}
            onChange={setSalesMngUserId}
            className="w-[140px]"
          />
        </SearchField>
      </SearchForm>

      <div className="flex items-center gap-6 mb-3 text-sm font-bold text-red-600">
        <span>총 합계(원) : {numberWithCommas(Number(sums.TOTAL_SUPPLY_UNIT_PRICE ?? 0))}</span>
      </div>

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