"use client";

import { useEffect, useMemo, useState } from "react";
import { Plus, Search, Trash2, History, ArrowRightLeft, Package } from "lucide-react";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";

interface Stock { OBJID: string; WH_OBJID: string; WH_CODE: string; WH_NAME: string; ITEM_OBJID: string; ITEM_CODE: string; ITEM_NAME: string; UNIT: string; IS_TAX_FREE: string; QTY: number; UPDATE_DATE: string }
interface Wh { OBJID: string; WH_CODE: string; WH_NAME: string }
interface Item { OBJID: string; ITEM_CODE: string; ITEM_NAME: string; UNIT_PRICE: number }
interface InboundLine { itemObjid: string; itemName: string; qty: number; costPrice?: number }

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");

export default function InventoryPage() {
  const router = useRouter();
  const [list, setList] = useState<Stock[]>([]);
  const [whs, setWhs] = useState<Wh[]>([]);
  const [items, setItems] = useState<Item[]>([]);
  const [whFilter, setWhFilter] = useState("");
  const [keyword, setKeyword] = useState("");
  const [inboundOpen, setInboundOpen] = useState(false);
  const [transferOpen, setTransferOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState<{ itemObjid: string; whObjid: string; itemName: string; whName: string } | null>(null);

  // 입고 폼
  const [inboundWh, setInboundWh] = useState("");
  const [lines, setLines] = useState<InboundLine[]>([]);
  const [pickItem, setPickItem] = useState("");
  const [pickQty, setPickQty] = useState(1);

  // 이동 폼
  const [trFrom, setTrFrom] = useState("");
  const [trTo, setTrTo] = useState("");
  const [trItem, setTrItem] = useState("");
  const [trQty, setTrQty] = useState(1);

  const load = async () => {
    const res = await fetch("/api/m/inventory/list", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ whObjid: whFilter || undefined, keyword: keyword || undefined }),
    });
    setList((await res.json()).RESULTLIST ?? []);
  };
  const loadMeta = async () => {
    const w = await (await fetch("/api/m/warehouses/list", { method: "POST" })).json();
    setWhs(w.RESULTLIST ?? []);
    const i = await (await fetch("/api/m/items/list", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) })).json();
    setItems(i.RESULTLIST ?? []);
  };

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

  const addLine = () => {
    if (!pickItem) return;
    const it = items.find((x) => x.OBJID === pickItem);
    if (!it) return;
    setLines([...lines, { itemObjid: it.OBJID, itemName: it.ITEM_NAME, qty: pickQty }]);
    setPickItem(""); setPickQty(1);
  };

  const submitInbound = async () => {
    if (!inboundWh || lines.length === 0) {
      Swal.fire({ icon: "warning", title: "창고와 품목을 입력하세요." });
      return;
    }
    const res = await fetch("/api/m/inventory/inbound", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        whObjid: inboundWh,
        lines: lines.map((l) => ({ itemObjid: l.itemObjid, qty: l.qty, costPrice: l.costPrice })),
      }),
    });
    const j = await res.json();
    if (j.success) {
      Swal.fire({ icon: "success", title: "입고 처리 완료", timer: 1500, showConfirmButton: false });
      setInboundOpen(false); setLines([]); setInboundWh("");
      load();
    } else {
      Swal.fire({ icon: "error", title: "오류", text: j.message });
    }
  };

  // 출발 창고에 재고가 있는 품목만 추리기 (현재 화면 list 기준)
  const trItemsInFrom = useMemo(() => {
    if (!trFrom) return [] as Stock[];
    return list.filter((s) => s.WH_OBJID === trFrom && Number(s.QTY) > 0);
  }, [list, trFrom]);

  const trCurrent = useMemo(() => {
    if (!trFrom || !trItem) return 0;
    return Number(list.find((s) => s.WH_OBJID === trFrom && s.ITEM_OBJID === trItem)?.QTY ?? 0);
  }, [list, trFrom, trItem]);

  const submitTransfer = async () => {
    if (!trFrom || !trTo || !trItem || trQty <= 0) {
      Swal.fire({ icon: "warning", title: "출발창고/도착창고/품목/수량을 입력하세요." });
      return;
    }
    if (trFrom === trTo) {
      Swal.fire({ icon: "warning", title: "출발창고와 도착창고가 같습니다." });
      return;
    }
    if (trQty > trCurrent) {
      Swal.fire({ icon: "warning", title: "재고 부족", text: `현재고 ${trCurrent}` });
      return;
    }
    const res = await fetch("/api/m/inventory/transfer", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fromWhObjid: trFrom, toWhObjid: trTo, itemObjid: trItem, qty: trQty }),
    });
    const j = await res.json().catch(() => ({ success: false, message: "응답 파싱 실패" }));
    if (j.success) {
      Swal.fire({ icon: "success", title: "재고 이동 완료", text: j.message, timer: 1500, showConfirmButton: false });
      setTransferOpen(false);
      setTrFrom(""); setTrTo(""); setTrItem(""); setTrQty(1);
      load();
    } else {
      Swal.fire({ icon: "error", title: "이동 실패", text: j.message });
    }
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h1 className="text-xl sm:text-2xl font-bold">재고 관리</h1>
        <div className="flex gap-2 flex-wrap">
          <button
            onClick={() => router.push("/m/admin/inventory/history")}
            className="h-9 sm:h-10 px-3 inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white text-slate-700 text-xs sm:text-sm font-semibold hover:bg-slate-50"
          >
            <History size={14} /> 이력
          </button>
          <button
            onClick={() => setTransferOpen(true)}
            className="h-9 sm:h-10 px-3 inline-flex items-center gap-1.5 rounded-lg bg-sky-600 text-white text-xs sm:text-sm font-bold hover:bg-sky-700"
          >
            <ArrowRightLeft size={14} /> 재고 이동
          </button>
          <button onClick={() => setInboundOpen(true)} className="h-9 sm:h-10 px-3 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={14} /> 매입 입고
          </button>
        </div>
      </div>

      {/* 검색 영역 — 모바일 1열 / sm 2열 / lg 옆으로 */}
      <div className="bg-white border border-slate-200 rounded-xl p-2.5">
        <div className="grid grid-cols-1 sm:grid-cols-[1fr_2fr_auto] gap-2">
          <select value={whFilter} onChange={(e) => setWhFilter(e.target.value)} className="h-9 px-3 rounded-lg border border-slate-200 text-sm bg-white">
            <option value="">전체 창고</option>
            {whs.map((w) => <option key={w.OBJID} value={w.OBJID}>{w.WH_NAME}</option>)}
          </select>
          <div className="relative">
            <Search size={14} 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-9 pl-8 pr-3 rounded-lg border border-slate-200 text-sm" />
          </div>
          <button onClick={load} className="h-9 px-4 rounded-lg bg-slate-800 text-white text-sm font-semibold">조회</button>
        </div>
      </div>

      {/* 데스크톱 테이블 */}
      <div className="hidden sm:block bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[640px]">
            <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-center px-4 py-3">구분</th>
                <th className="text-right px-4 py-3">현재고</th>
                <th className="text-left px-4 py-3">최종 변경</th>
                <th className="text-center px-4 py-3 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((s) => (
                <tr key={s.OBJID} className="border-t border-slate-100">
                  <td className="px-4 py-3">{s.WH_NAME}</td>
                  <td className="px-4 py-3 font-mono text-xs">{s.ITEM_CODE}</td>
                  <td className="px-4 py-3 font-semibold">{s.ITEM_NAME}</td>
                  <td className="px-4 py-3 text-center">
                    {s.IS_TAX_FREE === "Y"
                      ? <span className="px-1.5 py-0.5 rounded bg-violet-100 text-violet-700 text-[10px] font-bold">면세</span>
                      : <span className="px-1.5 py-0.5 rounded bg-rose-100 text-rose-700 text-[10px] font-bold">과세</span>}
                  </td>
                  <td className="px-4 py-3 text-right tabular-nums font-bold">{fmt(s.QTY)} {s.UNIT}</td>
                  <td className="px-4 py-3 text-slate-500 text-xs">{s.UPDATE_DATE}</td>
                  <td className="px-4 py-3 text-center">
                    <button onClick={() => setHistoryOpen({ itemObjid: s.ITEM_OBJID, whObjid: s.WH_OBJID, itemName: s.ITEM_NAME, whName: s.WH_NAME })}
                      className="inline-flex items-center gap-1 h-7 px-2 rounded bg-slate-100 hover:bg-slate-200 text-slate-700 text-[11px] font-bold">
                      <History size={12} /> 이력
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 모바일 카드 — 페이지 자체 스크롤 사용 (테이블 가로 스크롤 X) */}
      <div className="sm:hidden space-y-2">
        {list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl py-12 text-center text-slate-400 text-sm">
            <Package size={32} className="mx-auto mb-2 opacity-50" />
            재고 데이터가 없습니다.
          </div>
        ) : list.map((s) => (
          <div key={s.OBJID} className="bg-white border border-slate-200 rounded-xl p-3">
            <div className="flex items-start justify-between gap-2">
              <div className="min-w-0 flex-1">
                <div className="text-[10px] text-slate-400 font-mono">{s.ITEM_CODE}</div>
                <div className="font-bold text-sm text-slate-900 truncate">{s.ITEM_NAME}</div>
                <div className="text-[11px] text-slate-500 mt-0.5">{s.WH_NAME}</div>
              </div>
              <div className="text-right shrink-0">
                <div className="text-lg font-bold tabular-nums text-emerald-700">{fmt(s.QTY)}<span className="text-xs ml-0.5 text-slate-500">{s.UNIT}</span></div>
                {s.IS_TAX_FREE === "Y"
                  ? <span className="px-1.5 py-0.5 rounded bg-violet-100 text-violet-700 text-[9px] font-bold">면세</span>
                  : <span className="px-1.5 py-0.5 rounded bg-rose-100 text-rose-700 text-[9px] font-bold">과세</span>}
              </div>
            </div>
            <div className="mt-2 pt-2 border-t border-slate-100 text-[10px] text-slate-400 flex items-center justify-between">
              <span>최종 변경 · {s.UPDATE_DATE}</span>
              <button onClick={() => setHistoryOpen({ itemObjid: s.ITEM_OBJID, whObjid: s.WH_OBJID, itemName: s.ITEM_NAME, whName: s.WH_NAME })}
                className="inline-flex items-center gap-1 h-6 px-2 rounded bg-slate-100 text-slate-700 text-[10px] font-bold">
                <History size={10} /> 이력
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* 재고이력 모달 */}
      {historyOpen && (
        <StockHistoryModal
          itemObjid={historyOpen.itemObjid}
          whObjid={historyOpen.whObjid}
          itemName={historyOpen.itemName}
          whName={historyOpen.whName}
          onClose={() => setHistoryOpen(null)}
        />
      )}

      {/* 입고 모달 */}
      {inboundOpen && (
        <div className="fixed inset-0 bg-slate-900/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4" onClick={() => setInboundOpen(false)}>
          <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-t-xl sm:rounded-xl max-w-2xl w-full p-4 sm:p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="font-bold mb-4">매입 입고 등록</h3>
            <div className="space-y-3">
              <select value={inboundWh} onChange={(e) => setInboundWh(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 bg-white">
                <option value="">창고 선택</option>
                {whs.map((w) => <option key={w.OBJID} value={w.OBJID}>{w.WH_NAME}</option>)}
              </select>
              <div className="grid grid-cols-[1fr_80px_auto] gap-2">
                <select value={pickItem} onChange={(e) => setPickItem(e.target.value)} className="h-10 px-3 rounded-lg border border-slate-200 bg-white min-w-0">
                  <option value="">품목 선택</option>
                  {items.map((i) => <option key={i.OBJID} value={i.OBJID}>{i.ITEM_NAME}</option>)}
                </select>
                <input type="number" min={1} value={pickQty} onChange={(e) => setPickQty(Number(e.target.value))} className="h-10 px-3 rounded-lg border border-slate-200" />
                <button onClick={addLine} className="h-10 px-4 rounded-lg bg-slate-800 text-white text-sm font-semibold">추가</button>
              </div>
              <div className="border border-slate-200 rounded-lg max-h-60 overflow-y-auto">
                {lines.length === 0 ? (
                  <div className="text-center text-slate-400 text-sm py-8">품목을 추가하세요</div>
                ) : (
                  <table className="w-full text-sm">
                    <thead className="bg-slate-50 text-slate-600 text-xs sticky top-0">
                      <tr><th className="px-3 py-2 text-left">품목</th><th className="px-3 py-2 text-right">수량</th><th></th></tr>
                    </thead>
                    <tbody>
                      {lines.map((ln, i) => (
                        <tr key={i} className="border-t border-slate-100">
                          <td className="px-3 py-2">{ln.itemName}</td>
                          <td className="px-3 py-2 text-right">{ln.qty}</td>
                          <td className="px-3 py-2 text-right">
                            <button onClick={() => setLines(lines.filter((_, j) => j !== i))} className="text-slate-400 hover:text-rose-500"><Trash2 size={12} /></button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
            <div className="flex gap-2 justify-end mt-5">
              <button onClick={() => setInboundOpen(false)} className="px-4 h-10 rounded-lg border border-slate-200 text-sm font-semibold">취소</button>
              <button onClick={submitInbound} className="px-5 h-10 rounded-lg bg-emerald-700 text-white text-sm font-bold">입고 처리</button>
            </div>
          </div>
        </div>
      )}

      {/* 재고 이동 모달 — A창고 → B창고 */}
      {transferOpen && (
        <div className="fixed inset-0 bg-slate-900/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4" onClick={() => setTransferOpen(false)}>
          <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-t-xl sm:rounded-xl max-w-md w-full p-4 sm:p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="font-bold mb-1 inline-flex items-center gap-1.5"><ArrowRightLeft size={16} className="text-sky-600" /> 재고 이동</h3>
            <p className="text-xs text-slate-500 mb-4">A창고에서 B창고로 수량을 옮깁니다.</p>
            <div className="space-y-3">
              <div>
                <label className="block text-[11px] font-semibold text-slate-500 mb-1">출발 창고 (A)</label>
                <select value={trFrom} onChange={(e) => { setTrFrom(e.target.value); setTrItem(""); }} className="w-full h-10 px-3 rounded-lg border border-slate-200 bg-white">
                  <option value="">선택</option>
                  {whs.map((w) => <option key={w.OBJID} value={w.OBJID}>{w.WH_NAME}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-500 mb-1">도착 창고 (B)</label>
                <select value={trTo} onChange={(e) => setTrTo(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 bg-white">
                  <option value="">선택</option>
                  {whs.filter((w) => w.OBJID !== trFrom).map((w) => <option key={w.OBJID} value={w.OBJID}>{w.WH_NAME}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-500 mb-1">품목 {trFrom && <span className="text-slate-400">(출발창고 재고가 있는 품목만)</span>}</label>
                <select value={trItem} onChange={(e) => setTrItem(e.target.value)} disabled={!trFrom} className="w-full h-10 px-3 rounded-lg border border-slate-200 bg-white disabled:bg-slate-50">
                  <option value="">{trFrom ? "선택" : "출발창고 먼저 선택"}</option>
                  {trItemsInFrom.map((s) => (
                    <option key={s.ITEM_OBJID} value={s.ITEM_OBJID}>{s.ITEM_NAME} (재고 {fmt(s.QTY)} {s.UNIT})</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-500 mb-1">
                  이동 수량 {trItem && <span className="text-emerald-700 font-bold">최대 {fmt(trCurrent)}</span>}
                </label>
                <input type="number" min={1} max={trCurrent || undefined} value={trQty} onChange={(e) => setTrQty(Number(e.target.value))} className="w-full h-10 px-3 rounded-lg border border-slate-200 text-right tabular-nums" />
              </div>
            </div>
            <div className="flex gap-2 justify-end mt-5">
              <button onClick={() => setTransferOpen(false)} className="px-4 h-10 rounded-lg border border-slate-200 text-sm font-semibold">취소</button>
              <button onClick={submitTransfer} disabled={!trFrom || !trTo || !trItem || trQty <= 0} className="px-5 h-10 rounded-lg bg-sky-600 text-white text-sm font-bold disabled:opacity-50">이동</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

interface MoveRow {
  OBJID: string;
  MOVE_TYPE: string;
  MOVE_TYPE_NAME?: string;
  QTY: number;
  REF_TYPE: string;
  REF_TYPE_LABEL?: string;
  REF_OBJID: string;
  COUNTER_WH_NAME?: string | null;
  MEMO: string | null;
  REGID: string | null;
  REGDATE: string;
}

const MOVE_LABEL: Record<string, string> = { IN: "입고", OUT: "출고", ADJ: "조정", TRANSFER: "이동" };
const MOVE_COLOR: Record<string, string> = {
  IN: "bg-emerald-100 text-emerald-700",
  OUT: "bg-rose-100 text-rose-700",
  ADJ: "bg-amber-100 text-amber-700",
  TRANSFER: "bg-blue-100 text-blue-700",
};

function StockHistoryModal({
  itemObjid, whObjid, itemName, whName, onClose,
}: { itemObjid: string; whObjid: string; itemName: string; whName: string; onClose: () => void }) {
  const [moves, setMoves] = useState<MoveRow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const res = await fetch("/api/m/inventory/history", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ itemObjid, whObjid }),
      });
      const j = await res.json();
      if (!cancelled) {
        setMoves(j.RESULTLIST ?? []);
        setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [itemObjid, whObjid]);

  return (
    <div className="fixed inset-0 bg-slate-900/60 z-50 flex items-center justify-center p-3" onClick={onClose}>
      <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="px-4 py-3 border-b border-slate-200 flex items-center justify-between">
          <div>
            <h3 className="font-bold text-slate-900">{itemName} · 재고이력</h3>
            <p className="text-[11px] text-slate-500 mt-0.5">{whName}</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-700 p-1">✕</button>
        </div>
        <div className="overflow-y-auto p-3">
          {loading ? (
            <div className="text-center py-12 text-slate-400 text-sm">불러오는 중...</div>
          ) : moves.length === 0 ? (
            <div className="text-center py-12 text-slate-400 text-sm">이력이 없습니다.</div>
          ) : (
            <table className="w-full text-xs">
              <thead className="bg-slate-50 text-slate-600 sticky top-0">
                <tr>
                  <th className="text-left px-2 py-2">일시</th>
                  <th className="text-center px-2 py-2">구분</th>
                  <th className="text-right px-2 py-2">수량</th>
                  <th className="text-left px-2 py-2">참조</th>
                  <th className="text-left px-2 py-2">메모</th>
                  <th className="text-left px-2 py-2">담당</th>
                </tr>
              </thead>
              <tbody>
                {moves.map((m) => (
                  <tr key={m.OBJID} className="border-t border-slate-100">
                    <td className="px-2 py-2 whitespace-nowrap">{m.REGDATE}</td>
                    <td className="px-2 py-2 text-center">
                      <span className={`text-[10px] px-1.5 py-0.5 rounded font-bold ${MOVE_COLOR[m.MOVE_TYPE] ?? "bg-slate-100 text-slate-600"}`}>
                        {MOVE_LABEL[m.MOVE_TYPE] ?? m.MOVE_TYPE}
                      </span>
                    </td>
                    <td className={`px-2 py-2 text-right tabular-nums font-bold ${Number(m.QTY) < 0 ? "text-rose-600" : "text-emerald-700"}`}>
                      {Number(m.QTY) > 0 ? "+" : ""}{fmt(m.QTY)}
                    </td>
                    <td className="px-2 py-2 text-[11px] text-slate-700">
                      {m.REF_TYPE_LABEL || m.REF_TYPE || "-"}
                      {m.REF_TYPE === "TRANSFER" && m.COUNTER_WH_NAME && (
                        <span className="ml-1 text-slate-500">
                          {m.MOVE_TYPE === "OUT" ? `→ ${m.COUNTER_WH_NAME}` : `← ${m.COUNTER_WH_NAME}`}
                        </span>
                      )}
                    </td>
                    <td className="px-2 py-2 text-[11px] truncate max-w-[150px]">{m.MEMO || "-"}</td>
                    <td className="px-2 py-2 text-[11px] text-slate-500">{m.REGID || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}
