"use client";

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

interface Branch {
  CODE: string;
  NAME: string;
  BANK_ACCOUNT: string;
  PHONE: string | null;
  EMAIL: string | null;
  CEO_NAME: string | null;
  BIZ_NO: string | null;
  ADDRESS: string | null;
  IS_DEFAULT: string;
  SORT_ORDER: number;
}

export default function StatementBranchesPage() {
  const [list, setList] = useState<Branch[]>([]);
  const [editing, setEditing] = useState<Partial<Branch> | null>(null);
  const [isNew, setIsNew] = useState(false);

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

  const openNew = () => {
    setIsNew(true);
    setEditing({ CODE: "", NAME: "", BANK_ACCOUNT: "", IS_DEFAULT: "N", SORT_ORDER: list.length + 1 });
  };
  const openEdit = (b: Branch) => { setIsNew(false); setEditing({ ...b }); };

  const save = async (e: FormEvent) => {
    e.preventDefault();
    if (!editing) return;
    if (!editing.CODE || !editing.NAME || !editing.BANK_ACCOUNT) {
      Swal.fire({ icon: "warning", title: "코드/이름/계좌번호는 필수" });
      return;
    }
    const res = await fetch("/api/m/admin/statement-branches/save", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        actionType: isNew ? "regist" : "update",
        code: editing.CODE, name: editing.NAME, bankAccount: editing.BANK_ACCOUNT,
        phone: editing.PHONE ?? "", email: editing.EMAIL ?? "",
        ceoName: editing.CEO_NAME ?? "", bizNo: editing.BIZ_NO ?? "", address: editing.ADDRESS ?? "",
        isDefault: editing.IS_DEFAULT ?? "N", sortOrder: String(editing.SORT_ORDER ?? 0),
      }),
    });
    const j = await res.json();
    if (j.success) {
      await Swal.fire({ icon: "success", title: "저장 완료", timer: 1200, showConfirmButton: false });
      setEditing(null); load();
    } else {
      Swal.fire({ icon: "error", title: "저장 실패", text: j.message });
    }
  };

  const del = async (b: Branch) => {
    if (b.IS_DEFAULT === "Y") {
      Swal.fire({ icon: "warning", title: "기본 명세표는 삭제 불가" });
      return;
    }
    const ok = await Swal.fire({ icon: "question", title: `${b.NAME} (${b.CODE}) 삭제?`, showCancelButton: true });
    if (!ok.isConfirmed) return;
    const res = await fetch("/api/m/admin/statement-branches/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ actionType: "delete", code: b.CODE, name: b.NAME, bankAccount: b.BANK_ACCOUNT }),
    });
    if ((await res.json()).success) load();
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">기준 명세표 관리</h1>
          <p className="text-xs text-slate-500 mt-0.5">거래명세표/계산서에 표시될 공급자(모모유통) 정보. 사용자별 기준 명세서 설정에서 어느 코드를 사용할지 선택.</p>
        </div>
        <button onClick={openNew} className="h-9 px-3 rounded bg-emerald-700 text-white text-sm font-bold inline-flex items-center gap-1 hover:bg-emerald-800">
          <Plus size={14} /> 신규
        </button>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-slate-600 text-xs">
            <tr>
              <th className="px-3 py-2 text-left">코드</th>
              <th className="px-3 py-2 text-left">이름</th>
              <th className="px-3 py-2 text-left">결제 계좌</th>
              <th className="px-3 py-2 text-left">전화</th>
              <th className="px-3 py-2 text-left">이메일</th>
              <th className="px-3 py-2 text-center">기본</th>
              <th className="px-3 py-2 text-center w-[100px]">동작</th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={7} className="text-center py-12 text-slate-400">등록된 기준 명세표가 없습니다.</td></tr>
            ) : list.map((b) => (
              <tr key={b.CODE} className="border-t border-slate-100">
                <td className="px-3 py-2 font-mono font-semibold text-emerald-700">{b.CODE}</td>
                <td className="px-3 py-2 font-semibold">{b.NAME}</td>
                <td className="px-3 py-2 text-xs">{b.BANK_ACCOUNT}</td>
                <td className="px-3 py-2 text-xs">{b.PHONE}</td>
                <td className="px-3 py-2 text-xs text-blue-700">{b.EMAIL}</td>
                <td className="px-3 py-2 text-center">
                  {b.IS_DEFAULT === "Y" && <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 font-bold">기본</span>}
                </td>
                <td className="px-3 py-2 text-center">
                  <button onClick={() => openEdit(b)} className="text-emerald-700 hover:text-emerald-800 mr-2"><Pencil size={14} /></button>
                  <button onClick={() => del(b)} className="text-rose-500 hover:text-rose-600"><Trash2 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} className="bg-white rounded-xl shadow-xl w-full max-w-lg p-5" onClick={(e) => e.stopPropagation()}>
            <h3 className="font-bold text-lg mb-4">{isNew ? "기준 명세표 등록" : `기준 명세표 수정 (${editing.CODE})`}</h3>
            <div className="space-y-3">
              <Field label="코드 *">
                <input required disabled={!isNew} value={editing.CODE ?? ""}
                  onChange={(e) => setEditing({ ...editing, CODE: e.target.value.toUpperCase() })}
                  placeholder="HQ / KIMPO 등" className="w-full h-9 px-3 rounded border border-slate-200 text-sm font-mono disabled:bg-slate-100" />
              </Field>
              <Field label="이름 *">
                <input required value={editing.NAME ?? ""}
                  onChange={(e) => setEditing({ ...editing, NAME: e.target.value })}
                  className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
              </Field>
              <Field label="결제 계좌번호 *">
                <input required value={editing.BANK_ACCOUNT ?? ""}
                  onChange={(e) => setEditing({ ...editing, BANK_ACCOUNT: e.target.value })}
                  placeholder="예: 기업은행 434-115361-01-016 (이상용)"
                  className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
              </Field>
              <div className="grid grid-cols-2 gap-2">
                <Field label="전화">
                  <input value={editing.PHONE ?? ""} onChange={(e) => setEditing({ ...editing, PHONE: e.target.value })}
                    className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
                </Field>
                <Field label="이메일">
                  <input type="email" value={editing.EMAIL ?? ""} onChange={(e) => setEditing({ ...editing, EMAIL: e.target.value })}
                    className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
                </Field>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <Field label="대표자">
                  <input value={editing.CEO_NAME ?? ""} onChange={(e) => setEditing({ ...editing, CEO_NAME: e.target.value })}
                    className="w-full h-9 px-3 rounded 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-9 px-3 rounded border border-slate-200 text-sm" />
                </Field>
              </div>
              <Field label="주소">
                <input value={editing.ADDRESS ?? ""} onChange={(e) => setEditing({ ...editing, ADDRESS: e.target.value })}
                  className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
              </Field>
              <div className="grid grid-cols-2 gap-2">
                <label className="flex items-center gap-2 text-sm text-slate-700">
                  <input type="checkbox" checked={editing.IS_DEFAULT === "Y"}
                    onChange={(e) => setEditing({ ...editing, IS_DEFAULT: e.target.checked ? "Y" : "N" })}
                    className="w-4 h-4 accent-emerald-600" />
                  기본 명세표
                </label>
                <Field label="정렬순">
                  <input type="number" value={editing.SORT_ORDER ?? 0}
                    onChange={(e) => setEditing({ ...editing, SORT_ORDER: Number(e.target.value) })}
                    className="w-full h-9 px-3 rounded border border-slate-200 text-sm" />
                </Field>
              </div>
            </div>
            <div className="flex gap-2 justify-end mt-5">
              <button type="button" onClick={() => setEditing(null)} className="h-10 px-4 rounded-lg border border-slate-200 text-sm font-semibold">취소</button>
              <button type="submit" className="h-10 px-5 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 (
    <label className="block">
      <div className="text-[11px] font-semibold text-slate-600 mb-1">{label}</div>
      {children}
    </label>
  );
}
