"use client";

import { useEffect, useState, FormEvent } from "react";
import { Search, Pencil, Shield } from "lucide-react";
import Swal from "sweetalert2";

interface Customer {
  USER_ID: string;
  USER_NAME: string;
  EMAIL: string;
  CELL_PHONE: string;
  BIZ_NO: string;
  CEO_NAME: string;
  ADDRESS: string;
  STATUS: string;
  UNLIMITED_QTY: string;
  VIEW_HIDDEN: string;
  REGDATE: string;
}

export default function AdminCustomersPage() {
  const [list, setList] = useState<Customer[]>([]);
  const [keyword, setKeyword] = useState("");
  const [editing, setEditing] = useState<Partial<Customer> | null>(null);

  const load = async () => {
    const res = await fetch("/api/m/customers/list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ keyword }),
    });
    setList((await res.json()).RESULTLIST ?? []);
  };

  useEffect(() => { load(); }, []); // eslint-disable-line

  const onSave = async (e: FormEvent) => {
    e.preventDefault();
    if (!editing?.USER_ID) return;
    const res = await fetch("/api/m/customers/save", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        userId: editing.USER_ID,
        userName: editing.USER_NAME,
        email: editing.EMAIL,
        cellPhone: editing.CELL_PHONE,
        bizNo: editing.BIZ_NO,
        ceoName: editing.CEO_NAME,
        address: editing.ADDRESS,
        status: editing.STATUS,
        unlimitedQty: editing.UNLIMITED_QTY,
        viewHidden: editing.VIEW_HIDDEN,
      }),
    });
    const j = await res.json();
    if (j.success) {
      Swal.fire({ icon: "success", title: "저장되었습니다", timer: 1200, showConfirmButton: false });
      setEditing(null);
      load();
    } else {
      Swal.fire({ icon: "error", title: "저장 실패", text: j.message });
    }
  };

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-bold text-gray-800">거래처 회원 관리</h2>

      <div className="flex gap-2 items-center">
        <div className="relative flex-1 max-w-md">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && load()}
            placeholder="아이디·업체명·이메일 검색"
            className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm"
          />
        </div>
        <button onClick={load} className="h-10 px-4 rounded-lg bg-emerald-700 text-white text-sm font-semibold hover:bg-emerald-800">
          조회
        </button>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-slate-600 text-xs uppercase">
            <tr>
              <th className="text-left px-3 py-3">아이디</th>
              <th className="text-left px-3 py-3">업체명</th>
              <th className="text-left px-3 py-3">대표자</th>
              <th className="text-left px-3 py-3">연락처</th>
              <th className="text-left px-3 py-3">이메일</th>
              <th className="text-center px-3 py-3">상태</th>
              <th className="text-center px-3 py-3">제한해지</th>
              <th className="text-center px-3 py-3">숨김보기</th>
              <th className="text-center px-3 py-3">가입일</th>
              <th className="text-right px-3 py-3 w-[60px]">수정</th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={10} className="text-center py-12 text-slate-400">거래처 회원이 없습니다.</td></tr>
            ) : list.map((c) => (
              <tr key={c.USER_ID} className="border-t border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-2 font-mono text-xs">{c.USER_ID}</td>
                <td className="px-3 py-2 font-semibold">{c.USER_NAME}</td>
                <td className="px-3 py-2">{c.CEO_NAME || "-"}</td>
                <td className="px-3 py-2">{c.CELL_PHONE || "-"}</td>
                <td className="px-3 py-2 text-xs text-slate-600">{c.EMAIL || "-"}</td>
                <td className="px-3 py-2 text-center">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded ${c.STATUS === "active" ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-500"}`}>
                    {c.STATUS === "active" ? "활성" : c.STATUS}
                  </span>
                </td>
                <td className="px-3 py-2 text-center">
                  {c.UNLIMITED_QTY === "Y" ? (
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 font-bold">해지</span>
                  ) : <span className="text-slate-300">-</span>}
                </td>
                <td className="px-3 py-2 text-center">
                  {c.VIEW_HIDDEN === "Y" ? (
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-violet-100 text-violet-700 font-bold">보기</span>
                  ) : <span className="text-slate-300">-</span>}
                </td>
                <td className="px-3 py-2 text-center text-xs text-slate-500">{c.REGDATE}</td>
                <td className="px-3 py-2 text-right">
                  <button onClick={() => setEditing(c)} className="text-slate-400 hover:text-emerald-700 p-1">
                    <Pencil size={14} />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {editing && (
        <div className="fixed inset-0 bg-slate-900/60 z-50 flex items-center justify-center p-4" onClick={() => setEditing(null)}>
          <form
            onSubmit={onSave}
            onClick={(e) => e.stopPropagation()}
            className="bg-white rounded-xl shadow-xl max-w-2xl w-full p-6 max-h-[92vh] overflow-y-auto"
          >
            <h3 className="text-lg font-bold mb-5 text-slate-800 border-b pb-3">거래처 회원 수정</h3>

            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3">기본 정보</p>
            <div className="grid sm:grid-cols-2 gap-4 mb-5">
              <Field label="아이디 (이메일)">
                <input value={editing.USER_ID ?? ""} disabled
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm bg-slate-50 text-slate-500" />
              </Field>
              <Field label="업체명">
                <input value={editing.USER_NAME ?? ""}
                  onChange={(e) => setEditing({ ...editing, USER_NAME: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              </Field>
              <Field label="대표자">
                <input value={editing.CEO_NAME ?? ""}
                  onChange={(e) => setEditing({ ...editing, CEO_NAME: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              </Field>
              <Field label="연락처">
                <input value={editing.CELL_PHONE ?? ""}
                  onChange={(e) => setEditing({ ...editing, CELL_PHONE: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              </Field>
              <Field label="이메일">
                <input value={editing.EMAIL ?? ""}
                  onChange={(e) => setEditing({ ...editing, EMAIL: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              </Field>
              <Field label="사업자등록번호">
                <input value={editing.BIZ_NO ?? ""}
                  onChange={(e) => setEditing({ ...editing, BIZ_NO: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              </Field>
              <div className="sm:col-span-2">
                <Field label="주소">
                  <input value={editing.ADDRESS ?? ""}
                    onChange={(e) => setEditing({ ...editing, ADDRESS: e.target.value })}
                    className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
                </Field>
              </div>
              <Field label="상태">
                <select
                  value={editing.STATUS ?? "active"}
                  onChange={(e) => setEditing({ ...editing, STATUS: e.target.value })}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm bg-white"
                >
                  <option value="active">활성</option>
                  <option value="inactive">비활성</option>
                </select>
              </Field>
            </div>

            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3 mt-2 border-t pt-4 flex items-center gap-2">
              <Shield size={12} className="text-amber-600" />
              특수 권한
            </p>
            <div className="space-y-3 mb-5">
              <label className="flex items-center gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer">
                <input
                  type="checkbox"
                  checked={editing.UNLIMITED_QTY === "Y"}
                  onChange={(e) => setEditing({ ...editing, UNLIMITED_QTY: e.target.checked ? "Y" : "N" })}
                  className="w-4 h-4"
                />
                <div className="flex-1">
                  <div className="text-sm font-semibold text-slate-800">제한수량 해지</div>
                  <div className="text-xs text-slate-500">품목별 1회 발주 제한수량(max_order_qty)을 무시하고 재고만큼 발주 가능</div>
                </div>
              </label>
              <label className="flex items-center gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer">
                <input
                  type="checkbox"
                  checked={editing.VIEW_HIDDEN === "Y"}
                  onChange={(e) => setEditing({ ...editing, VIEW_HIDDEN: e.target.checked ? "Y" : "N" })}
                  className="w-4 h-4"
                />
                <div className="flex-1">
                  <div className="text-sm font-semibold text-slate-800">숨김처리 보기</div>
                  <div className="text-xs text-slate-500">관리자가 숨김(is_hidden=Y)으로 등록한 품목도 발주 화면에 표시</div>
                </div>
              </label>
            </div>

            <div className="flex justify-end gap-2 pt-4 border-t">
              <button type="button" onClick={() => setEditing(null)} className="px-4 h-10 rounded-lg border border-slate-200 text-sm font-semibold hover:bg-slate-50">
                취소
              </button>
              <button type="submit" className="px-5 h-10 rounded-lg bg-emerald-700 text-white text-sm font-bold hover:bg-emerald-800">
                저장
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-slate-600 mb-1.5">{label}</label>
      {children}
    </div>
  );
}
