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

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

// 원본: purchaseOrder/deliveryMngStatus.jsp
// 입고관리 > 현황 — 프로젝트 BOM별 발주/입고/부적합 집계 리포트
export default function DeliveryStatusPage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [projectNo, setProjectNo] = useState(""); // 단일 project objid
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const [customerOptions, setCustomerOptions] = useState<Option[]>([]);
  const [projectOptions, setProjectOptions] = useState<Option[]>([]);

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

    fetch("/api/common/project-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: "{}",
    })
      .then((r) => r.json())
      .then((d) =>
        setProjectOptions(
          (d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.LABEL || r.PROJECT_NO || r.CUSTOMER_PROJECT_NAME || r.OBJID),
          })),
        ),
      )
      .catch(() => {});
  }, []);

  // 구매BOM 팝업
  const openBomPopup = (bomReportObjId: string) => {
    if (!bomReportObjId) return;
    const w = 1600;
    const h = 900;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/bom/form?parentObjId=${bomReportObjId}&actType=view`,
      `bomReport_${bomReportObjId}`,
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  const columns: GridColumn[] = [
    {
      title: "프로젝트정보",
      headerHozAlign: "center",
      frozen: true,
      columns: [
        { title: "고객사", field: "CUSTOMER_NAME", width: 110, hozAlign: "left" },
        { title: "프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 140, hozAlign: "left" },
        { title: "유닛명", field: "UNIT_PART_NAME", width: 200, hozAlign: "left" },
        { title: "프로젝트번호", field: "PROJECT_NO", width: 100, hozAlign: "left" },
      ],
    },
    {
      title: "발주내역",
      headerHozAlign: "center",
      columns: [
        {
          title: "구매BOM",
          field: "TOTAL_BOM_PART_CNT",
          width: 80,
          hozAlign: "center",
          cellClick: (row) => openBomPopup(String(row.BOM_REPORT_OBJID || "")),
          formatter: (cell) => (Number(cell) > 0 ? "조회" : "-"),
        },
        { title: "전체품목수", field: "TOTAL_BOM_PART_CNT", width: 100, hozAlign: "right", formatter: "money" },
        { title: "발주품목수", field: "TOTAL_PO_PART_CNT", width: 100, hozAlign: "right", formatter: "money" },
        { title: "발주율(%)", field: "PO_RATE", width: 90, hozAlign: "right" },
        { title: "미발주품수", field: "NON_PO_PART_CNT", width: 90, hozAlign: "right", formatter: "money" },
        { title: "총수량", field: "TOTAL_BOM_PART_QTY_SUM", width: 90, hozAlign: "right", formatter: "money" },
      ],
    },
    {
      title: "입고현황",
      headerHozAlign: "center",
      columns: [
        { title: "발주수량(신)", field: "TOTAL_PO_NEW_QTY", width: 95, hozAlign: "right", formatter: "money" },
        { title: "발주수량(재)", field: "TOTAL_PO_RE_QTY", width: 95, hozAlign: "right", formatter: "money" },
        { title: "입고수량", field: "DELIVERY_QTY", width: 90, hozAlign: "right", formatter: "money" },
        { title: "미입고수량", field: "NON_DELIVERY_QTY", width: 90, hozAlign: "right", formatter: "money" },
      ],
    },
    {
      title: "수입검사결과(불량현황)",
      headerHozAlign: "center",
      columns: [
        { title: "부적합수량", field: "TOTAL_DEFECT_QTY", width: 90, hozAlign: "right", formatter: "money" },
        { title: "불량률(%)", field: "DELIVERY_RATE", width: 90, hozAlign: "right" },
        { title: "설계오류", field: "DEFECT_QTY_1", width: 80, hozAlign: "right", formatter: "money" },
        { title: "제작불량", field: "DEFECT_QTY_2", width: 80, hozAlign: "right", formatter: "money" },
        { title: "구매오류", field: "DEFECT_QTY_3", width: 80, hozAlign: "right", formatter: "money" },
        { title: "오품반입", field: "DEFECT_QTY_4", width: 80, hozAlign: "right", formatter: "money" },
        { title: "손실비용", field: "TOTAL_DEFECT_PRICE", width: 90, hozAlign: "right", formatter: "money" },
      ],
    },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/delivery/status", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        Year: year,
        customer_objid: customerObjid,
        project_nos: projectNo ? [projectNo] : [],
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [year, customerObjid, projectNo]);

  useEffect(() => {
    fetchData();
    // 최초 1회만
    // 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>
        </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: 5 }, (_, i) => currentYear - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="고객사">
          <SearchableSelect
            options={customerOptions}
            value={customerObjid}
            onChange={setCustomerObjid}
            className="w-[180px]"
          />
        </SearchField>
        <SearchField label="프로젝트번호">
          <SearchableSelect
            options={projectOptions}
            value={projectNo}
            onChange={setProjectNo}
            className="w-[240px]"
          />
        </SearchField>
      </SearchForm>

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