"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 { getStdCategoryByAlias } from "@/lib/procurement-std";
import Swal from "sweetalert2";

// 구매품표준관리 공통 컴포넌트
// codeGroupId = "CODE1"~"CODE5" → procurement_standard 카테고리 관리
// codeGroupId = "MATERIAL_CODE" → part_mng 자재코드 관리
interface StandardCodePageProps {
  title: string;
  codeGroupId: string;
}

const API_URL = "/api/procurement-std";

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

export default function StandardCodePage({ title, codeGroupId }: StandardCodePageProps) {
  const isMaterial = codeGroupId === "MATERIAL_CODE";
  const stdDef = isMaterial ? null : getStdCategoryByAlias(codeGroupId);

  // 자재코드 검색
  const [partNo, setPartNo] = useState("");
  const [largeCd, setLargeCd] = useState("");
  const [middleCd, setMiddleCd] = useState("");
  const [maker, setMaker] = useState("");
  const [partName, setPartName] = useState("");
  const [spec, setSpec] = useState("");
  // 코드관리 검색
  const [codeName, setCodeName] = useState("");
  const [codeId, setCodeId] = useState("");

  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const openCodeForm = useCallback(
    (objId: string) => {
      const url = `/procurement-std/popup/code-form?alias=${codeGroupId}&objId=${encodeURIComponent(objId)}`;
      openPopup(url, "codeFormPopup", 500, 320);
    },
    [codeGroupId]
  );

  const openMaterialForm = useCallback((objId: string, readOnly = false) => {
    const url = `/procurement-std/popup/material-form?objId=${encodeURIComponent(objId)}&readOnly=${readOnly}`;
    openPopup(url, "materialFormPopup", 1200, 420);
  }, []);

  const materialColumns: GridColumn[] = [
    {
      title: "자재코드",
      field: "PART_NO",
      width: 150,
      hozAlign: "center",
      cellClick: (row) => openMaterialForm(String(row.OBJID), true),
    },
    { title: "대분류", field: "MAJOR_CATEGORY", width: 100, hozAlign: "left" },
    { title: "CODE1", field: "CODE1", width: 70, hozAlign: "center" },
    { title: "중분류", field: "SUB_CATEGORY", width: 120, hozAlign: "left" },
    { title: "CODE2", field: "CODE2", width: 70, hozAlign: "center" },
    { title: "Maker", field: "MAKER", width: 120, hozAlign: "left" },
    { title: "CODE3", field: "CODE3", width: 70, hozAlign: "center" },
    { title: "품명", field: "PART_NAME", width: 160, hozAlign: "left" },
    { title: "CODE4", field: "CODE4", width: 70, hozAlign: "center" },
    { title: "규격", field: "SPEC", width: 160, hozAlign: "left" },
    { title: "CODE5", field: "CODE5", width: 70, hozAlign: "center" },
    { title: "Revision", field: "REVISION", width: 80, hozAlign: "center" },
    { title: "EO No", field: "EO_NO", width: 100, hozAlign: "center" },
    { title: "EO Date", field: "EO_DATE", width: 100, hozAlign: "center" },
  ];

  const codeColumns: GridColumn[] = [
    {
      title: "Code",
      field: "CODE_ID",
      width: 120,
      hozAlign: "center",
      cellClick: (row) => openCodeForm(String(row.OBJID)),
    },
    ...(stdDef?.showDetail
      ? [{ title: "상세내용", field: "DETAIL", width: 250, hozAlign: "left" as const }]
      : []),
    { title: "구분", field: "CODE_NAME", width: 250, hozAlign: "left" },
    { title: "등록일", field: "REG_DATE", width: 120, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 120, hozAlign: "center" },
  ];

  const columns = isMaterial ? materialColumns : codeColumns;

  const fetchData = useCallback(async () => {
    const bodyData = isMaterial
      ? {
          code_group: codeGroupId,
          part_no: partNo,
          large_cd: largeCd,
          middle_cd: middleCd,
          maker,
          part_name: partName,
          spec,
        }
      : { code_group: codeGroupId, code_name: codeName, code_id: codeId };

    const res = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(bodyData),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [codeGroupId, isMaterial, partNo, largeCd, middleCd, maker, partName, spec, codeName, codeId]);

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

  // 팝업에서 저장 후 호출할 수 있도록 window에 노출 (opener.fn_search)
  useEffect(() => {
    (window as unknown as { fn_search?: () => void }).fn_search = fetchData;
    return () => {
      delete (window as unknown as { fn_search?: () => void }).fn_search;
    };
  }, [fetchData]);

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire({ icon: "warning", title: "삭제할 항목을 선택하세요." });
      return;
    }
    const result = await Swal.fire({
      title: "삭제하시겠습니까?",
      text: `선택한 ${selectedRows.length}건을 삭제합니다.`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "확인",
      cancelButtonText: "취소",
    });
    if (!result.isConfirmed) return;

    const res = await fetch(API_URL, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        objIds: selectedRows.map((r) => String(r.OBJID)),
        mode: isMaterial ? "material" : "code",
      }),
    });
    const json = await res.json();
    if (json.success) {
      await Swal.fire({ icon: "success", title: json.message, timer: 1200, showConfirmButton: false });
      fetchData();
    } else {
      Swal.fire("오류", json.message, "error");
    }
  };

  const handleRegister = () => {
    if (isMaterial) openMaterialForm("");
    else openCodeForm("");
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">{title}</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={handleRegister}>등록</Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        {isMaterial ? (
          <>
            <SearchField label="자재코드">
              <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[140px]" />
            </SearchField>
            <SearchField label="대분류">
              <Input value={largeCd} onChange={(e) => setLargeCd(e.target.value)} className="w-[140px]" />
            </SearchField>
            <SearchField label="중분류">
              <Input value={middleCd} onChange={(e) => setMiddleCd(e.target.value)} className="w-[140px]" />
            </SearchField>
            <SearchField label="Maker">
              <Input value={maker} onChange={(e) => setMaker(e.target.value)} className="w-[140px]" />
            </SearchField>
            <SearchField label="품명">
              <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[140px]" />
            </SearchField>
            <SearchField label="사양(규격)">
              <Input value={spec} onChange={(e) => setSpec(e.target.value)} className="w-[140px]" />
            </SearchField>
          </>
        ) : (
          <>
            <SearchField label="구분">
              <Input value={codeName} onChange={(e) => setCodeName(e.target.value)} className="w-[200px]" />
            </SearchField>
            <SearchField label="Code">
              <Input value={codeId} onChange={(e) => setCodeId(e.target.value)} className="w-[150px]" />
            </SearchField>
          </>
        )}
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox
        height="calc(100vh - 400px)"
        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
