"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 { CodeSelect } from "@/components/ui/code-select";
import { Button } from "@/components/ui/button";
import { Pagination } from "@/components/ui/pagination";
import Swal from "sweetalert2";

// productmgmtList.jsp 대응 - 제품마스터
export default function ProductMgmtPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [productCategory, setProductCategory] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);
  const countPerPage = 20;

  const columns: GridColumn[] = [
    { title: "사업부", field: "PRODUCT_CATEGORY_NAME", width: 120,
      cellClick: (row) => openProductFormPopup(String(row.OBJID)) },
    { title: "제품군", field: "PRODUCT_TYPE_NAME", width: 100, hozAlign: "left" },
    { title: "제품명", field: "PRODUCT_NAME", width: 180, hozAlign: "left" },
    { title: "제품코드", field: "PRODUCT_CODE", width: 130, hozAlign: "left" },
    { title: "등록자", field: "WRITER_NAME", width: 100, hozAlign: "center" },
    { title: "등록일", field: "REGDATE", width: 110, hozAlign: "center" },
    { title: "생산여부", field: "PRODUCTION_FLAG_NAME", width: 100, hozAlign: "center" },
    { title: "첨부", field: "FILE_CNT", width: 60, hozAlign: "center",
      formatter: (_cell, row) => Number(row.FILE_CNT || 0) > 0 ? "📎" : "" },
  ];

  const fetchData = useCallback(async (page = 1) => {
    const res = await fetch("/api/product-mgmt", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year, product_category: productCategory, page, countPerPage }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
      setTotalCount(json.TOTAL_CNT || 0);
      setCurrentPage(page);
    }
  }, [year, productCategory]);

  const handleSearch = () => {
    fetchData(1);
  };

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("선택한 항목이 없습니다.");
      return;
    }

    const result = await Swal.fire({
      title: "삭제 확인",
      text: `${selectedRows.length}건을 삭제하시겠습니까?`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "삭제",
      cancelButtonText: "취소",
    });

    if (result.isConfirmed) {
      const res = await fetch("/api/product-mgmt", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ objIds: selectedRows.map((r) => r.OBJID) }),
      });
      const json = await res.json();
      if (json.success) {
        Swal.fire({ icon: "success", title: "삭제되었습니다.", timer: 1500, showConfirmButton: false });
        fetchData(currentPage);
      } else {
        Swal.fire({ icon: "error", title: json.message || "삭제 실패" });
      }
    }
  };

  const openProductFormPopup = (objId?: string) => {
    // TODO: 모달 다이얼로그로 대체 (기존 window.open popup 대응)
    const url = objId
      ? `/product-mgmt/form?objId=${objId}`
      : `/product-mgmt/form?actionType=regist`;
    window.open(url, "productForm", "width=850,height=480");
  };

  // 페이지 진입 시 자동 로드
  useEffect(() => { fetchData(); }, [fetchData]);

  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" onClick={() => openProductFormPopup()}>등록</Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" variant="secondary" onClick={handleSearch}>조회</Button>
        </div>
      </div>

      {/* 검색 영역 (productmgmtList.jsp #plmSearchZon 대응) */}
      <SearchForm onSearch={handleSearch}>
        <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="사업부">
          <CodeSelect
            codeId="0000917"
            value={productCategory}
            onChange={setProductCategory}
            placeholder="전체"
            className="w-[150px]"
          />
        </SearchField>
      </SearchForm>

      {/* 그리드 (Tabulator/plm_table 대응) */}
      <DataGrid
        columns={columns}
        data={data}
        showCheckbox
        onSelectionChange={setSelectedRows}

      />

      {/* 페이징 */}
      <Pagination
        currentPage={currentPage}
        maxPage={Math.ceil(totalCount / countPerPage)}
        totalCount={totalCount}
        onPageChange={(page) => fetchData(page)}
      />
    </div>
  );
}
