"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 Swal from "sweetalert2";

// 구매관리 > 공급업체관리 — 원본: /admin/supplyMngPagingList.do (admin_supply_mng)
export default function SupplierPage() {
  const [supplyCode, setSupplyCode] = useState("");
  const [supplyName, setSupplyName] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const openSupplierForm = (objId?: string) => {
    const url = objId ? `/purchase/supplier/form?objid=${objId}` : "/purchase/supplier/form";
    const w = 1300;
    const h = 620;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(url, "supplierForm", `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    { title: "NO", field: "RNUM", width: 50, hozAlign: "center" },
    { title: "구분", field: "SUPPLY_CODE_NAME", width: 90, hozAlign: "center" },
    {
      title: "고객명",
      field: "SUPPLY_NAME",
      width: 190,
      hozAlign: "left",
      cellClick: (row) => openSupplierForm(row.OBJID as string),
    },
    { title: "지역", field: "AREA_CD_NAME", width: 110, hozAlign: "center" },
    { title: "대표자명", field: "CHARGE_USER_NAME", width: 90, hozAlign: "center" },
    { title: "업종", field: "SUPPLY_STOCKNAME", width: 280, hozAlign: "left" },
    { title: "업태", field: "SUPPLY_BUSNAME", width: 180, hozAlign: "left" },
    { title: "주소", field: "SUPPLY_ADDRESS", width: 250, hozAlign: "left" },
    { title: "핸드폰", field: "SUPPLY_TEL_NO", width: 150, hozAlign: "center" },
    { title: "등록일", field: "REGDATE", width: 110, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/admin/supply", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ supply_code: supplyCode, supply_name: supplyName }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [supplyCode, supplyName]);

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

    const res = await fetch("/api/admin/supply/delete", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objIds: selectedRows.map((r) => String(r.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");
    }
  };

  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" variant="secondary" onClick={fetchData}>
            조회
          </Button>
          <Button size="sm" onClick={() => openSupplierForm()}>
            공급업체 등록
          </Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>
            삭제
          </Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="구분">
          <SearchableCodeSelect
            codeId="0000167"
            value={supplyCode}
            onChange={setSupplyCode}
            placeholder="전체"
            className="w-[160px]"
          />
        </SearchField>
        <SearchField label="고객명">
          <Input
            value={supplyName}
            onChange={(e) => setSupplyName(e.target.value)}
            placeholder="고객명"
            className="w-[180px]"
          />
        </SearchField>
      </SearchForm>

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

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