"use client";

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

interface Warehouse {
  OBJID: string; WH_CODE: string; WH_NAME: string; LOCATION: string; WH_TYPE: string;
}
// 본사/김포 각각 창고/용차/시장 + 김포지사 자체 = 총 7가지
const TYPE_LABEL: Record<string, string> = {
  HQ_STOCK:    "본사 창고",
  HQ_CHARTER:  "본사 용차",
  HQ_MARKET:   "본사 시장",
  KIMPO_BRANCH:"김포지사",
  KIMPO_STOCK: "김포 창고",
  KIMPO_CHARTER:"김포 용차",
  KIMPO_MARKET:"김포 시장",
  // ↓ 옛 enum (기존 데이터 표시 유지)
  STOCK:       "본사 창고",
  KIMPO:       "김포 창고",
  PICKUP_TEAM: "창고픽업팀",
  MARKET:      "시장픽업",
  DELIVERY:    "용차배송",
};
const TYPE_COLOR: Record<string, string> = {
  HQ_STOCK:     "bg-emerald-100 text-emerald-700",
  HQ_CHARTER:   "bg-orange-100 text-orange-700",
  HQ_MARKET:    "bg-amber-100 text-amber-700",
  KIMPO_BRANCH: "bg-teal-100 text-teal-700",
  KIMPO_STOCK:  "bg-teal-100 text-teal-700",
  KIMPO_CHARTER:"bg-orange-100 text-orange-700",
  KIMPO_MARKET: "bg-amber-100 text-amber-700",
  STOCK:        "bg-emerald-100 text-emerald-700",
  KIMPO:        "bg-teal-100 text-teal-700",
  PICKUP_TEAM:  "bg-sky-100 text-sky-700",
  MARKET:       "bg-amber-100 text-amber-700",
  DELIVERY:     "bg-orange-100 text-orange-700",
};
// 신규 카테고리 (select 옵션). 옛 enum 은 데이터 표시만 유지, 신규 추가는 새 enum 만.
const NEW_TYPE_ORDER = ["HQ_STOCK", "HQ_CHARTER", "HQ_MARKET", "KIMPO_BRANCH", "KIMPO_STOCK", "KIMPO_CHARTER", "KIMPO_MARKET"];

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

  const load = async () => {
    const res = await fetch("/api/m/warehouses/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/warehouses/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        objid: editing.OBJID, actionType: editing.OBJID ? "update" : "regist",
        whName: editing.WH_NAME,
        location: editing.LOCATION, whType: editing.WH_TYPE || "HQ_STOCK",
      }),
    });
    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({ WH_TYPE: "HQ_STOCK" })}
          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="grid grid-cols-1 sm:hidden gap-2">
        {list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl p-8 text-center text-slate-400">등록된 창고가 없습니다.</div>
        ) : list.map((w) => (
          <button key={w.OBJID} onClick={() => setEditing(w)}
            className="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">
              <WarehouseIcon size={16} className="text-emerald-700 shrink-0" />
              <span className="font-semibold text-sm flex-1 truncate">{w.WH_NAME}</span>
              <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${TYPE_COLOR[w.WH_TYPE] || "bg-slate-100 text-slate-700"}`}>
                {TYPE_LABEL[w.WH_TYPE] || w.WH_TYPE}
              </span>
              <Pencil size={14} className="text-slate-300" />
            </div>
            <div className="text-[11px] text-slate-500 pl-6">
              <span className="font-mono">{w.WH_CODE}</span>{w.LOCATION && ` · ${w.LOCATION}`}
            </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-[600px]">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="text-left px-4 py-3 w-24">코드</th>
              <th className="text-left px-4 py-3">이름</th>
              <th className="text-left px-4 py-3 w-32">유형</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={5} className="text-center py-12 text-slate-400">등록된 창고가 없습니다.</td></tr>
            ) : list.map((w) => (
              <tr key={w.OBJID} className="border-t border-slate-100 hover:bg-slate-50">
                <td className="px-4 py-3 font-mono text-xs">{w.WH_CODE}</td>
                <td className="px-4 py-3 font-semibold">{w.WH_NAME}</td>
                <td className="px-4 py-3">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${TYPE_COLOR[w.WH_TYPE] || "bg-slate-100 text-slate-700"}`}>
                    {TYPE_LABEL[w.WH_TYPE] || w.WH_TYPE}
                  </span>
                </td>
                <td className="px-4 py-3 text-slate-500">{w.LOCATION || "-"}</td>
                <td className="px-4 py-3 text-right">
                  <button onClick={() => setEditing(w)} 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-md 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="space-y-3">
              <div>
                <label className="block text-[11px] font-semibold text-slate-500 mb-1">코드 <span className="text-slate-400 font-normal">(자동 생성, 수정 불가)</span></label>
                <input
                  readOnly
                  value={editing.OBJID ? (editing.WH_CODE ?? "") : "등록 시 자동 생성"}
                  className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm bg-slate-50 text-slate-500 font-mono"
                />
              </div>
              <input required placeholder="이름" value={editing.WH_NAME ?? ""} onChange={(e) => setEditing({ ...editing, WH_NAME: e.target.value })} className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm" />
              <select value={editing.WH_TYPE ?? "HQ_STOCK"} onChange={(e) => setEditing({ ...editing, WH_TYPE: e.target.value })} className="w-full h-10 px-3 rounded-lg border border-slate-200 text-sm bg-white">
                {NEW_TYPE_ORDER.map((k) => <option key={k} value={k}>{TYPE_LABEL[k]}</option>)}
              </select>
              <input placeholder="위치 (선택)" value={editing.LOCATION ?? ""} onChange={(e) => setEditing({ ...editing, LOCATION: e.target.value })} className="w-full 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>
  );
}
