"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 { FolderCell } from "@/components/ui/folder-cell";
import { numberWithCommas } from "@/lib/utils";
import Swal from "sweetalert2";

const openBomPopup = (objId: string) => {
  if (!objId) return;
  const w = 1800, h = 800;
  const left = (window.screen.width - w) / 2;
  const top = (window.screen.height - h) / 2;
  window.open(
    `/purchase/bom/structure?objId=${objId}&readonly=1`,
    `bomStructure_${objId}`,
    `width=${w},height=${h},left=${left},top=${top}`,
  );
};

// 원본: /purchaseOrder/purchaseOrderStatusByProject.do (발주관리_현황)
export default function OrderStatusPage() {
  const [year, setYear] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [sums, setSums] = useState<Record<string, unknown>>({});
  const [loading, setLoading] = useState(false);

  const columns: GridColumn[] = [
    {
      title: "프로젝트정보",
      columns: [
        { title: "고객사", field: "CUSTOMER_NAME", width: 110, hozAlign: "left", frozen: true },
        { title: "프로젝트번호", field: "PROJECT_NO", width: 110, hozAlign: "left", frozen: true },
        { title: "유닛명", field: "UNIT_PART_NAME", width: 220, hozAlign: "left" },
        { title: "프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 130, hozAlign: "left" },
      ],
    },
    {
      title: "발주현황",
      columns: [
        {
          title: "구매BOM",
          field: "BOM_CNT",
          width: 80,
          hozAlign: "center",
          formatter: (cell, row) => (
            <FolderCell
              count={cell}
              onClick={() => openBomPopup(String(row.BOM_REPORT_OBJID || ""))}
            />
          ),
        },
        { title: "전체수량", field: "TOTAL_BOM_PART_CNT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "발주품수", field: "TOTAL_PO_PART_CNT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "미발주품수", field: "NON_PO_PART_CNT", width: 80, hozAlign: "right", formatter: "money" },
        {
          title: "발주율",
          field: "RATE_PO",
          width: 80,
          hozAlign: "right",
          formatter: (cell) => `${Number(cell) || 0}%`,
        },
        { title: "구매품", field: "PRICE_PT_1", width: 100, hozAlign: "right", formatter: "money" },
        { title: "제작품", field: "PRICE_PT_2", width: 100, hozAlign: "right", formatter: "money" },
        { title: "사급품", field: "PRICE_PT_3", width: 100, hozAlign: "right", formatter: "money" },
        { title: "기타", field: "PRICE_PT_ETC", width: 100, hozAlign: "right", formatter: "money" },
      ],
    },
    {
      title: "재발주현황",
      columns: [
        { title: "건수", field: "RE_COUNT", width: 70, hozAlign: "right", formatter: "money" },
        { title: "금액(원)", field: "RE_PRICE", width: 120, hozAlign: "right", formatter: "money" },
      ],
    },
    {
      title: "턴키현황",
      columns: [
        { title: "건수", field: "TURNKEY_COUNT", width: 70, hozAlign: "right", formatter: "money" },
        { title: "금액(원)", field: "TURNKEY_PRICE", width: 120, hozAlign: "right", formatter: "money" },
      ],
    },
    { title: "총발주금액(원)", field: "TOTAL_PRICE_ALL", width: 140, hozAlign: "right", formatter: "money" },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/order/status", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ year, project_no: projectNo }),
      });
      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]);

  const handleReset = () => {
    setYear("");
    setProjectNo("");
  };

  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-[200px]"
          />
        </SearchField>
      </SearchForm>

      <div className="flex items-center gap-6 mb-3 text-sm font-bold text-red-600">
        <span>총발주금액(원) : {numberWithCommas(Number(sums.TOTAL_PRICE_ALL_SUM ?? 0))}</span>
        <span>단일발주금액(원) : {numberWithCommas(Number(sums.SINGLE_PRICE_SUM ?? 0))}</span>
      </div>

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