"use client";

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

interface Vendor { OBJID: string; VENDOR_NAME: string; CONTACT: string; PHONE: string; BIZ_NO: string; EMAIL: string; ADDRESS: string }

export default function VendorsPage() {
  const [list, setList] = useState<Vendor[]>([]);
  const [editing, setEditing] = useState<Partial<Vendor> | null>(null);

  const load = async () => {
    const res = await fetch("/api/m/vendors/list", { method: "POST" });
    setList((await res.json()).RESULTLIST ?? []);
  };
  useEffect(() => { load(); }, []);

  const save = async (e: FormEvent) => {
    e.preventDefault();
    if (!editing) return;
    const res = await fetch("/api/m/vendors/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        objid: editing.OBJID, actionType: editing.OBJID ? "update" : "regist",
        vendorName: editing.VENDOR_NAME, contact: editing.CONTACT, phone: editing.PHONE,
        bizNo: editing.BIZ_NO, email: editing.EMAIL, address: editing.ADDRESS,
      }),
    });
    if ((await res.json()).success) {
      Swal.fire({ icon: "success", title: "저장됨", timer: 1200, showConfirmButton: false });
      setEditing(null); load();
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold">공급업체 관리</h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">모모유통이 제품을 매입하는 도매처 / 제조사 — 총 {list.length}개</p>
        </div>
        <button onClick={() => setEditing({})}
          className="h-10 px-3 sm:px-4 inline-flex items-center gap-1.5 rounded-lg bg-emerald-700 text-white text-xs sm:text-sm font-bold hover:bg-emerald-800">
          <Plus size={16} /> 추가
        </button>
      </div>

      {/* 모바일: 카드 리스트 */}
      <div className="space-y-2 sm:hidden">
        {list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl p-8 text-center text-slate-400">
            등록된 공급업체가 없습니다.
          </div>
        ) : list.map((v) => (
          <button key={v.OBJID} onClick={() => setEditing(v)}
            className="w-full bg-white border border-slate-200 rounded-xl p-3 shadow-sm text-left hover:bg-slate-50 active:bg-emerald-50">
            <div className="flex items-center gap-2 mb-1.5">
              <Building2 size={16} className="text-emerald-700 shrink-0" />
              <span className="font-semibold text-sm flex-1 truncate">{v.VENDOR_NAME}</span>
              <Pencil size={14} className="text-slate-300" />
            </div>
            <div className="text-[11px] text-slate-600 space-y-0.5 pl-6">
              <div>📞 {v.PHONE || "-"} {v.CONTACT && `· ${v.CONTACT}`}</div>
              {v.EMAIL && <div className="truncate">✉ {v.EMAIL}</div>}
              {v.BIZ_NO && <div>🏢 {v.BIZ_NO}</div>}
            </div>
          </button>
        ))}
      </div>

      {/* 데스크탑: 표 */}
      <div className="hidden sm:block bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm min-w-[700px]">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="text-left px-4 py-3">공급업체명</th>
              <th className="text-left px-4 py-3">담당자</th>
              <th className="text-left px-4 py-3">연락처</th>
              <th className="text-left px-4 py-3">사업자번호</th>
              <th className="text-left px-4 py-3">이메일</th>
              <th className="text-right px-4 py-3 w-[60px]"></th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={6} className="text-center py-12 text-slate-400">등록된 공급업체가 없습니다.</td></tr>
            ) : list.map((v) => (
              <tr key={v.OBJID} className="border-t border-slate-100 hover:bg-slate-50">
                <td className="px-4 py-3 font-semibold">{v.VENDOR_NAME}</td>
                <td className="px-4 py-3">{v.CONTACT || "-"}</td>
                <td className="px-4 py-3">{v.PHONE || "-"}</td>
                <td className="px-4 py-3">{v.BIZ_NO || "-"}</td>
                <td className="px-4 py-3 text-slate-500 text-xs">{v.EMAIL || "-"}</td>
                <td className="px-4 py-3 text-right">
                  <button onClick={() => setEditing(v)} className="text-slate-500 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-3" onClick={() => setEditing(null)}>
          <form onSubmit={save} onClick={(e) => e.stopPropagation()}
            className="bg-white rounded-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="font-bold text-base sm:text-lg mb-4">{editing.OBJID ? "공급업체 수정" : "공급업체 추가"}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <input required placeholder="공급업체명 *" value={editing.VENDOR_NAME ?? ""} onChange={(e) => setEditing({ ...editing, VENDOR_NAME: e.target.value })} className="sm:col-span-2 h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <input placeholder="담당자" value={editing.CONTACT ?? ""} onChange={(e) => setEditing({ ...editing, CONTACT: e.target.value })} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <input placeholder="연락처" value={editing.PHONE ?? ""} onChange={(e) => setEditing({ ...editing, PHONE: e.target.value })} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <input placeholder="사업자번호" value={editing.BIZ_NO ?? ""} onChange={(e) => setEditing({ ...editing, BIZ_NO: e.target.value })} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <input placeholder="이메일 (발주서 메일 받을 곳)" value={editing.EMAIL ?? ""} onChange={(e) => setEditing({ ...editing, EMAIL: e.target.value })} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <input placeholder="주소" value={editing.ADDRESS ?? ""} onChange={(e) => setEditing({ ...editing, ADDRESS: e.target.value })} className="sm:col-span-2 h-10 px-3 rounded-lg border border-slate-200 text-sm" />
            </div>
            <div className="flex gap-2 justify-end mt-5">
              <button type="button" onClick={() => setEditing(null)} className="px-4 h-10 rounded-lg border border-slate-200 text-sm font-semibold">취소</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>
  );
}
