"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";

// 영업관리 > 고객관리 (원본: contractMgmt/supplyMngList.jsp)
export default function CustomerPage() {
  const [supplyName, setSupplyName] = useState("");
  const [supplyCode, setSupplyCode] = useState("");
  const [areaCd, setAreaCd] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const openPopup = (objid: string = "") => {
    const q = objid ? `?objid=${encodeURIComponent(objid)}` : "";
    window.open(`/sales/customer/form${q}`, "customerForm", "width=900,height=560");
  };

  const columns: GridColumn[] = [
    {
      title: "고객번호", field: "CUS_NO", width: 110,
      cellClick: (row) => openPopup(String(row.OBJID || "")),
    },
    { title: "고객구분", field: "SUPPLY_CODE_NAME", width: 100 },
    { title: "지역", field: "AREA_CD_NAME", width: 110 },
    { title: "고객사", field: "SUPPLY_NAME", width: 220 },
    { title: "대표자명", field: "CHARGE_USER_NAME", width: 110 },
    { title: "사업자등록번호", field: "BUS_REG_NO", width: 140 },
    { title: "주소", field: "SUPPLY_ADDRESS", width: 280 },
    { title: "연락처", field: "SUPPLY_TEL_NO", width: 130 },
    { title: "E-MAIL", field: "EMAIL", width: 220 },
    { title: "등록일", field: "REGDATE", width: 110, hozAlign: "center" },
  ];

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

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택한 항목이 없습니다.", "warning");
      return;
    }
    const r = await Swal.fire({
      title: "선택한 고객정보를 삭제하시겠습니까?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "확인",
      cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;
    const res = await fetch("/api/sales/customer/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: "삭제되었습니다.", 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="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
          <Button size="sm" onClick={() => openPopup()}>고객등록</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="고객사명">
          <Input value={supplyName} onChange={(e) => setSupplyName(e.target.value)} className="w-[200px]" />
        </SearchField>
        <SearchField label="고객구분">
          <SearchableCodeSelect codeId="0000167" value={supplyCode} onChange={setSupplyCode} className="w-[180px]" />
        </SearchField>
        <SearchField label="지역">
          <SearchableCodeSelect codeId="0000172" value={areaCd} onChange={setAreaCd} className="w-[180px]" />
        </SearchField>
      </SearchForm>

      <div className="text-xs text-gray-500 mb-2">총 {data.length}건</div>

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

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