"use client";

import { useEffect, useState, useCallback } from "react";

interface Move {
  OBJID: string;
  WH_NAME: string;
  WH_CODE: string;
  ITEM_CODE: string;
  ITEM_NAME: string;
  UNIT: 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;
  REGID: string;
  REGDATE: string;
}

interface Wh { OBJID: string; WH_NAME: string }

const MOVE_TYPE_BADGE: 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",
};

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

export default function InventoryHistoryPage() {
  const [list, setList] = useState<Move[]>([]);
  const [whs, setWhs] = useState<Wh[]>([]);
  const [loading, setLoading] = useState(false);

  const [whFilter, setWhFilter] = useState("");
  const [moveType, setMoveType] = useState("");
  const [keyword, setKeyword] = useState("");
  const [dateFrom, setDateFrom] = useState(() => {
    const d = new Date();
    d.setDate(1);
    return d.toISOString().slice(0, 10);
  });
  const [dateTo, setDateTo] = useState(() => new Date().toISOString().slice(0, 10));

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/inventory/history", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          whObjid: whFilter || undefined,
          moveType: moveType || undefined,
          keyword: keyword || undefined,
          dateFrom: dateFrom || undefined,
          dateTo: dateTo || undefined,
        }),
      });
      setList((await res.json()).RESULTLIST ?? []);
    } finally {
      setLoading(false);
    }
  }, [whFilter, moveType, keyword, dateFrom, dateTo]);

  const loadWhs = async () => {
    const res = await fetch("/api/m/warehouses/list", { method: "POST" });
    setWhs((await res.json()).RESULTLIST ?? []);
  };

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

  const inTotal = list.filter((r) => r.MOVE_TYPE === "IN").reduce((s, r) => s + Number(r.QTY), 0);
  const outTotal = list.filter((r) => r.MOVE_TYPE === "OUT").reduce((s, r) => s + Number(r.QTY), 0);

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h1 className="text-xl sm:text-2xl font-bold text-slate-800">재고 이력 조회</h1>
      </div>

      {/* 검색 영역 — 모바일 1열 → sm 2열 → lg 5열 */}
      <div className="bg-white border border-slate-200 rounded-xl p-3">
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">창고</label>
            <select value={whFilter} onChange={(e) => setWhFilter(e.target.value)}
              className="w-full h-9 px-2 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>
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">이동 유형</label>
            <select value={moveType} onChange={(e) => setMoveType(e.target.value)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm bg-white">
              <option value="">전체</option>
              <option value="IN">입고</option>
              <option value="OUT">출고</option>
              <option value="ADJ">재고조정</option>
              <option value="TRANSFER">이동</option>
            </select>
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">시작일</label>
            <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">종료일</label>
            <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
          <div className="col-span-2 sm:col-span-3 lg:col-span-1">
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">품목 검색</label>
            <input value={keyword} onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && load()}
              placeholder="품목명/코드"
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
        </div>
        <div className="flex justify-end mt-2">
          <button onClick={load} disabled={loading}
            className="h-9 px-5 rounded-lg bg-slate-800 text-white text-sm font-semibold disabled:opacity-50">
            {loading ? "조회 중..." : "조회"}
          </button>
        </div>
      </div>

      {/* 요약 카드 */}
      <div className="grid grid-cols-3 gap-2 sm:gap-3">
        <div className="bg-white border border-slate-200 rounded-xl p-3 sm:p-4 text-center">
          <p className="text-[11px] sm:text-xs text-slate-500 mb-1">총 이력</p>
          <p className="text-lg sm:text-2xl font-bold text-slate-800 tabular-nums">{list.length.toLocaleString()}<span className="text-xs font-normal ml-0.5">건</span></p>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-3 sm:p-4 text-center">
          <p className="text-[11px] sm:text-xs text-slate-500 mb-1">입고 합계</p>
          <p className="text-lg sm:text-2xl font-bold text-emerald-700 tabular-nums">+{fmt(inTotal)}</p>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-3 sm:p-4 text-center">
          <p className="text-[11px] sm:text-xs text-slate-500 mb-1">출고 합계</p>
          <p className="text-lg sm:text-2xl font-bold text-rose-600 tabular-nums">-{fmt(outTotal)}</p>
        </div>
      </div>

      {/* 데스크톱 테이블 (sm 이상) */}
      <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-[760px]">
            <thead className="bg-slate-50 text-slate-600">
              <tr>
                <th className="text-center px-3 py-3 w-[80px]">유형</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-right px-3 py-3 w-[90px]">수량</th>
                <th className="text-left px-3 py-3 w-[80px]">참조</th>
                <th className="text-left px-3 py-3">메모</th>
                <th className="text-left px-3 py-3 w-[80px]">처리자</th>
                <th className="text-center px-3 py-3 w-[130px]">일시</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={9} className="text-center py-12 text-slate-400">조회 중...</td></tr>
              ) : list.length === 0 ? (
                <tr><td colSpan={9} className="text-center py-12 text-slate-400">이력이 없습니다.</td></tr>
              ) : (
                list.map((m) => (
                  <tr key={m.OBJID} className="border-t border-slate-100 hover:bg-slate-50">
                    <td className="px-3 py-2 text-center">
                      <span className={`text-[11px] px-2 py-0.5 rounded font-bold ${MOVE_TYPE_BADGE[m.MOVE_TYPE] || "bg-slate-100 text-slate-600"}`}>
                        {m.MOVE_TYPE_NAME}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-slate-700 text-xs">{m.WH_NAME || "-"}</td>
                    <td className="px-3 py-2 font-mono text-xs text-slate-500">{m.ITEM_CODE}</td>
                    <td className="px-3 py-2 font-semibold text-slate-800">{m.ITEM_NAME}</td>
                    <td className="px-3 py-2 text-right tabular-nums font-bold">
                      <span className={m.MOVE_TYPE === "OUT" ? "text-rose-600" : "text-emerald-700"}>
                        {m.MOVE_TYPE === "OUT" ? "-" : "+"}{fmt(m.QTY)}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-xs 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-3 py-2 text-xs text-slate-500 max-w-[200px] truncate">{m.MEMO || "-"}</td>
                    <td className="px-3 py-2 text-xs text-slate-500">{m.REGID || "-"}</td>
                    <td className="px-3 py-2 text-center text-xs text-slate-500">{m.REGDATE}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        {list.length > 0 && (
          <div className="px-4 py-2 border-t border-slate-100 text-xs text-slate-400 text-right">최대 500건 표시</div>
        )}
      </div>

      {/* 모바일 카드 (sm 미만) — 페이지 자체 스크롤 */}
      <div className="sm:hidden space-y-2">
        {loading ? (
          <div className="bg-white border border-slate-200 rounded-xl py-12 text-center text-slate-400 text-sm">조회 중...</div>
        ) : list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl py-12 text-center text-slate-400 text-sm">이력이 없습니다.</div>
        ) : list.map((m) => (
          <div key={m.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="flex items-center gap-1.5 mb-1">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded font-bold ${MOVE_TYPE_BADGE[m.MOVE_TYPE] || "bg-slate-100 text-slate-600"}`}>
                    {m.MOVE_TYPE_NAME}
                  </span>
                  {m.REF_TYPE && <span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">{m.REF_TYPE_LABEL || m.REF_TYPE}{m.REF_TYPE === "TRANSFER" && m.COUNTER_WH_NAME && (m.MOVE_TYPE === "OUT" ? ` → ${m.COUNTER_WH_NAME}` : ` ← ${m.COUNTER_WH_NAME}`)}</span>}
                </div>
                <div className="font-bold text-sm text-slate-900 truncate">{m.ITEM_NAME}</div>
                <div className="text-[10px] text-slate-400 font-mono">{m.ITEM_CODE}</div>
                <div className="text-[11px] text-slate-500 mt-1">{m.WH_NAME || "-"}</div>
              </div>
              <div className="text-right shrink-0">
                <div className={`text-xl font-bold tabular-nums ${m.MOVE_TYPE === "OUT" ? "text-rose-600" : "text-emerald-700"}`}>
                  {m.MOVE_TYPE === "OUT" ? "-" : "+"}{fmt(m.QTY)}
                </div>
                <div className="text-[10px] text-slate-400">{m.UNIT}</div>
              </div>
            </div>
            {m.MEMO && <div className="mt-2 pt-2 border-t border-slate-100 text-[11px] text-slate-600 line-clamp-2">{m.MEMO}</div>}
            <div className="mt-2 pt-2 border-t border-slate-100 flex items-center justify-between text-[10px] text-slate-400">
              <span>{m.REGID || "-"}</span>
              <span>{m.REGDATE}</span>
            </div>
          </div>
        ))}
        {list.length > 0 && (
          <div className="text-center text-[10px] text-slate-400 py-2">최대 500건 표시</div>
        )}
      </div>
    </div>
  );
}
