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

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

// 원본: /salesMng/salesBomReportList.do
export default function PurchaseBomPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [customerCd, setCustomerCd] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [unitName, setUnitName] = useState("");
  const [writer2Id, setWriter2Id] = useState("");
  const [customerOptions, setCustomerOptions] = useState<Option[]>([]);
  const [userOptions, setUserOptions] = useState<Option[]>([]);
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  useEffect(() => {
    fetch("/api/admin/supply", { 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/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 openStructurePopup = (objId: string) => {
    if (!objId) return;
    const w = 1800, h = 800;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/bom/structure?objId=${objId}&readonly=1`,
      "bomStructure",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openSalesBomReport = (objId: string, sbrObjId: string) => {
    if (!objId) return;
    const w = 1900, h = 900;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/bom/form?parentObjId=${objId}&objId=${sbrObjId || ""}`,
      "salesMngReport",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 110, hozAlign: "left" },
    { title: "요청납기", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
    { title: "수주회사", field: "CONTRACT_COMPANY_NAME", width: 110, hozAlign: "left" },
    { title: "제작공장", field: "MANUFACTURE_PLANT_NAME", width: 90, hozAlign: "center" },
    { title: "유닛명", field: "UNIT_NAME", width: 220, hozAlign: "left" },
    {
      title: "E-BOM",
      field: "BOM_CNT",
      width: 80,
      hozAlign: "center",
      formatter: (cell, row) => (
        <FolderCell count={cell} onClick={() => openStructurePopup(String(row.OBJID || ""))} />
      ),
    },
    { title: "배포일", field: "DEPLOY_DATE", width: 100, hozAlign: "center" },
    { title: "설계담당자", field: "WRITER1_NAME", width: 100, hozAlign: "center" },
    {
      title: "구매BOM",
      field: "SALES_PART_CNT",
      width: 90,
      hozAlign: "center",
      formatter: (cell, row) => (
        <FolderCell
          count={cell}
          onClick={() => openSalesBomReport(String(row.OBJID || ""), String(row.SBR_OBJID || ""))}
        />
      ),
    },
    { title: "작성일", field: "REGDATE2", width: 100, hozAlign: "center" },
    { title: "구매담당자", field: "WRITER2_NAME", width: 100, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/purchase/bom", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        customer_cd: customerCd,
        project_no: projectNo,
        unit_name: unitName,
        writer2_id: writer2Id,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [year, customerCd, projectNo, unitName, writer2Id]);

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

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">구매BOM관리</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) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>
                {y}
              </option>
            ))}
          </select>
        </SearchField>
        <SearchField label="고객사">
          <SearchableSelect
            options={customerOptions}
            value={customerCd}
            onChange={setCustomerCd}
            className="w-[180px]"
            placeholder="전체"
          />
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input
            value={projectNo}
            onChange={(e) => setProjectNo(e.target.value)}
            placeholder="프로젝트번호"
            className="w-[160px]"
          />
        </SearchField>
        <SearchField label="유닛명">
          <Input
            value={unitName}
            onChange={(e) => setUnitName(e.target.value)}
            placeholder="유닛명"
            className="w-[160px]"
          />
        </SearchField>
        <SearchField label="구매담당자">
          <SearchableSelect
            options={userOptions}
            value={writer2Id}
            onChange={setWriter2Id}
            className="w-[160px]"
            placeholder="전체"
          />
        </SearchField>
      </SearchForm>

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