"use client";

import { useState, useCallback, useEffect } from "react";
import Swal from "sweetalert2";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Button } from "@/components/ui/button";
import { SearchableCodeSelect } from "@/components/ui/searchable-code-select";

// 프로젝트관리 > 제품구분_UNIT관리 (project/wbsTemplateMngList.do 대응)
export default function WbsTemplatePage() {
  const [product, setProduct] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const openCenterPopup = (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 columns: GridColumn[] = [
    { title: "제품구분", field: "PRODUCT_NAME", width: 250, hozAlign: "left" },
    { title: "기계형식", field: "TITLE", width: 250, hozAlign: "left" },
    {
      title: "고객사_장비목적",
      field: "CUSTOMER_PRODUCT",
      hozAlign: "left",
      cellClick: (row) => {
        openCenterPopup(
          `/project/wbs-template/master-form?objId=${row.OBJID}`,
          "openTemplateMasterPopUp",
          1000,
          200,
        );
      },
    },
    {
      title: "UNIT",
      field: "WBS_TASK_CNT",
      width: 250,
      hozAlign: "center",
      formatter: (cell) => `📁 ${cell ?? 0}`,
      cellClick: (row) => {
        openCenterPopup(
          `/project/wbs-template/task-list?objId=${row.OBJID}`,
          "openWBSTaskListPopUp",
          800,
          700,
        );
      },
    },
    { title: "등록자", field: "WRITER_TITLE", width: 250, hozAlign: "left" },
    { title: "등록일", field: "REG_DATE_TITLE", width: 250, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/project/wbs-template", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ product }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [product]);

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

  const handleRegister = () => {
    if (!product) {
      Swal.fire("알림", "제품은 필수값입니다. 제품을 선택해 주세요.", "warning");
      return;
    }
    openCenterPopup(
      `/project/wbs-template/excel-import?product=${encodeURIComponent(product)}`,
      "openWBSExcelImportPopUp",
      1340,
      700,
    );
  };

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 대상이 없습니다.", "warning");
      return;
    }
    const r = await Swal.fire({
      title: "삭제하시겠습니까?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "확인",
      cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;
    const res = await fetch("/api/project/wbs-template/delete", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objIds: selectedRows.map((row) => String(row.OBJID)) }),
    });
    const json = await res.json();
    if (json.success) {
      Swal.fire({ icon: "success", title: json.message, timer: 1200, showConfirmButton: false });
      fetchData();
    } else {
      Swal.fire("오류", json.message, "error");
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">프로젝트관리_제품구분_UNIT관리</h2>
        <div className="flex gap-2">
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" onClick={handleRegister}>등록</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="제품구분">
          <SearchableCodeSelect
            codeId="0000001"
            value={product}
            onChange={setProduct}
            className="w-[200px]"
          />
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox

        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
