"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 { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import { FolderCell } from "@/components/ui/folder-cell";
import * as XLSX from "xlsx";
import Swal from "sweetalert2";

// 제품관리_PART 조회 (원본: partMng/partMngList.jsp)
export default function PartListPage() {
  const [searchPartNo, setSearchPartNo] = useState("");
  const [searchPartName, setSearchPartName] = useState("");
  const [searchRevision, setSearchRevision] = useState("0"); // 원본 JSP 기본값 = all
  const [searchMaterial, setSearchMaterial] = useState("");
  const [searchSpec, setSearchSpec] = useState("");
  const [searchPartType, setSearchPartType] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);

  const centerPopup = (url: string, name: string, w: number, h: number) => {
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(url, name, `width=${w},height=${h},left=${left},top=${top},menubars=no,scrollbars=yes,resizable=yes`);
  };

  const openPartDetail = (objId: string) => {
    centerPopup(`/product/popup/part-form?objId=${encodeURIComponent(objId)}`, "partMngPopUp", 900, 600);
  };

  const openFilePopup = (objId: string, docType: string, docTypeName: string) => {
    centerPopup(
      `/common/files?targetObjId=${encodeURIComponent(objId)}&docType=${encodeURIComponent(docType)}&docTypeName=${encodeURIComponent(docTypeName)}`,
      "fileRegistPopUp",
      800,
      335,
    );
  };

  const columns: GridColumn[] = [
    {
      title: "품번", field: "PART_NO", width: 125, hozAlign: "left",
      cellClick: (row) => openPartDetail(String(row.OBJID)),
    },
    {
      title: "품명", field: "PART_NAME", hozAlign: "left",
      cellClick: (row) => openPartDetail(String(row.OBJID)),
    },
    { title: "수량", field: "BOM_QTY", width: 50, hozAlign: "center" },
    {
      title: "3D", field: "CU01_CNT", width: 45, hozAlign: "center",
      formatter: (cell) => <FolderCell count={cell} />,
      cellClick: (row) => openFilePopup(String(row.OBJID), "3D_CAD", "3D CAD 첨부파일"),
    },
    {
      title: "2D", field: "CU02_CNT", width: 45, hozAlign: "center",
      formatter: (cell) => <FolderCell count={cell} />,
      cellClick: (row) => openFilePopup(String(row.OBJID), "2D_DRAWING_CAD", "2D(Drawing) CAD 첨부파일"),
    },
    {
      title: "PDF", field: "CU03_CNT", width: 55, hozAlign: "center",
      formatter: (cell) => <FolderCell count={cell} />,
      cellClick: (row) => openFilePopup(String(row.OBJID), "2D_PDF_CAD", "2D(PDF) CAD 첨부파일"),
    },
    { title: "재질", field: "MATERIAL", width: 90, hozAlign: "left" },
    { title: "사양(규격)", field: "SPEC", width: 90, hozAlign: "left" },
    { title: "후처리", field: "POST_PROCESSING", width: 80, hozAlign: "left" },
    { title: "MAKER", field: "MAKER", width: 80, hozAlign: "left" },
    { title: "대분류", field: "MAJOR_CATEGORY", width: 80, hozAlign: "left" },
    { title: "중분류", field: "SUB_CATEGORY", width: 80, hozAlign: "left" },
    { title: "Revision", field: "REVISION", width: 80, hozAlign: "center" },
    { title: "EO No", field: "EO_NO", width: 90, hozAlign: "center" },
    { title: "EO Date", field: "EO_DATE", width: 80, hozAlign: "center" },
    { title: "PART구분", field: "PART_TYPE_TITLE", width: 88, hozAlign: "center" },
    { title: "비고", field: "REMARK", width: 80, hozAlign: "left" },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/product/part", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          mode: "list",
          SEARCH_PART_NO: searchPartNo,
          SEARCH_PART_NAME: searchPartName,
          SEARCH_REVISION_RELEASE: searchRevision,
          SEARCH_MATERIAL: searchMaterial,
          SEARCH_SPEC: searchSpec,
          SEARCH_PART_TYPE: searchPartType,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } catch {
      Swal.fire("오류", "데이터 조회 중 오류가 발생했습니다.", "error");
    } finally {
      setLoading(false);
    }
  }, [searchPartNo, searchPartName, searchRevision, searchMaterial, searchSpec, searchPartType]);

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

  const handleExcel = () => {
    if (data.length === 0) {
      Swal.fire("알림", "다운로드할 데이터가 없습니다.", "warning");
      return;
    }
    const header = [
      "품번", "품명", "수량", "3D", "2D", "PDF", "재질", "사양(규격)",
      "후처리", "MAKER", "대분류", "중분류", "Revision", "EO No",
      "EO Date", "PART구분", "비고",
    ];
    const body = data.map((r) => [
      r.PART_NO ?? "", r.PART_NAME ?? "", r.BOM_QTY ?? "",
      r.CU01_CNT ?? 0, r.CU02_CNT ?? 0, r.CU03_CNT ?? 0,
      r.MATERIAL ?? "", r.SPEC ?? "", r.POST_PROCESSING ?? "",
      r.MAKER ?? "", r.MAJOR_CATEGORY ?? "", r.SUB_CATEGORY ?? "",
      r.REVISION ?? "", r.EO_NO ?? "", r.EO_DATE ?? "",
      r.PART_TYPE_TITLE ?? "", r.REMARK ?? "",
    ]);
    const ws = XLSX.utils.aoa_to_sheet([header, ...body]);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "PART 조회");
    const today = new Date().toISOString().slice(0, 10);
    XLSX.writeFile(wb, `PART_조회_${today}.xlsx`);
  };

  const handleReset = () => {
    setSearchPartNo(""); setSearchPartName(""); setSearchRevision("0");
    setSearchMaterial(""); setSearchSpec(""); setSearchPartType("");
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">제품관리_PART 조회</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={fetchData}>조회</Button>
          <Button size="sm" variant="secondary" onClick={handleReset}>초기화</Button>
          <Button size="sm" variant="secondary" onClick={handleExcel}>Excel Download</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="품번">
          <Input value={searchPartNo} onChange={(e) => setSearchPartNo(e.target.value)} className="w-[194px]" />
        </SearchField>
        <SearchField label="품명">
          <Input value={searchPartName} onChange={(e) => setSearchPartName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="Revision">
          <select
            value={searchRevision}
            onChange={(e) => setSearchRevision(e.target.value)}
            className="h-9 w-[150px] rounded border border-gray-300 bg-white px-2 text-sm"
          >
            <option value="1">current</option>
            <option value="0">all</option>
          </select>
        </SearchField>
        <SearchField label="재질">
          <Input value={searchMaterial} onChange={(e) => setSearchMaterial(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="사양(규격)">
          <Input value={searchSpec} onChange={(e) => setSearchSpec(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="부품 유형">
          <SearchableCodeSelect codeId="0000062" value={searchPartType} onChange={setSearchPartType} className="w-[150px]" />
        </SearchField>
      </SearchForm>

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