"use client";

import { useCallback, useEffect, useState } from "react";
import { ArrowRightLeft, RefreshCcw, Download } from "lucide-react";
import { downloadXlsx } from "@/lib/xlsx-export";

interface Row {
  OBJID: string; MOVED_AT: string;
  ITEM_CODE: string; ITEM_NAME: string; UNIT: string;
  COST_PRICE: number; QTY: number; AMOUNT: number;
  FROM_WH: string; FROM_CODE: string;
  TO_WH: string; TO_CODE: string;
  MEMO: string | null; REGID: string; REG_USER_NAME: string | null;
}

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const todayStr = () => new Date().toISOString().slice(0, 10);
const monthAgo = () => { const d = new Date(); d.setMonth(d.getMonth() - 1); return d.toISOString().slice(0, 10); };

export default function TransfersPage() {
  const [dateFrom, setDateFrom] = useState(monthAgo());
  const [dateTo, setDateTo] = useState(todayStr());
  const [rows, setRows] = useState<Row[]>([]);
  const [totals, setTotals] = useState({ qty: 0, amount: 0 });
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/admin/transfers", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ dateFrom, dateTo }),
      });
      const j = await res.json();
      setRows(j.RESULTLIST ?? []);
      setTotals({ qty: Number(j.TOTAL_QTY ?? 0), amount: Number(j.TOTAL_AMOUNT ?? 0) });
    } finally { setLoading(false); }
  }, [dateFrom, dateTo]);

  useEffect(() => { load(); }, [load]);

  const onExport = () => {
    if (rows.length === 0) return;
    downloadXlsx(`창고이동_${dateFrom}_${dateTo}`, rows, [
      { header: "이동일시", key: "MOVED_AT" },
      { header: "품목코드", key: "ITEM_CODE" },
      { header: "품목명",   key: "ITEM_NAME" },
      { header: "단위",     key: "UNIT" },
      { header: "수량",     key: (r) => Number(r.QTY) },
      { header: "단가",     key: (r) => Number(r.COST_PRICE) },
      { header: "금액",     key: (r) => Number(r.AMOUNT) },
      { header: "출발창고", key: (r) => `${r.FROM_WH ?? ""} (${r.FROM_CODE ?? ""})` },
      { header: "도착창고", key: (r) => `${r.TO_WH ?? ""} (${r.TO_CODE ?? ""})` },
      { header: "메모",     key: (r) => r.MEMO ?? "" },
      { header: "이동자ID", key: "REGID" },
      { header: "이동자",   key: (r) => r.REG_USER_NAME ?? "" },
    ]);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-end justify-between flex-wrap gap-2">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2">
            <ArrowRightLeft size={20} className="text-sky-700" />
            창고 이동 통계
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            창고 간 이동 이력 (TRANSFER). 수량 × 단가(cost_price) = 이동 금액. 이동자/날짜/시간 포함.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
            className="h-9 px-3 rounded border border-slate-300 text-sm" />
          <span className="text-slate-400">~</span>
          <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
            className="h-9 px-3 rounded border border-slate-300 text-sm" />
          <button onClick={load} disabled={loading}
            className="h-9 px-3 rounded bg-slate-800 text-white text-sm font-bold inline-flex items-center gap-1 hover:bg-slate-900 disabled:opacity-50">
            <RefreshCcw size={14} /> 조회
          </button>
          <button onClick={onExport} disabled={rows.length === 0}
            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 disabled:opacity-50">
            <Download size={14} /> 엑셀
          </button>
        </div>
      </div>

      {/* 합계 카드 */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-500 mb-1">이동 건수</div>
          <div className="text-xl font-bold tabular-nums">{fmt(rows.length)}건</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-500 mb-1">총 이동 수량</div>
          <div className="text-xl font-bold tabular-nums">{fmt(totals.qty)}</div>
        </div>
        <div className="bg-sky-50 border border-sky-200 rounded-xl p-4">
          <div className="text-[11px] text-sky-700 mb-1 font-semibold">총 이동 금액 (단가 기준)</div>
          <div className="text-xl font-bold text-sky-700 tabular-nums">₩{fmt(totals.amount)}</div>
        </div>
      </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="text-left px-3 py-2">이동일시</th>
              <th className="text-left px-3 py-2">품목</th>
              <th className="text-right px-3 py-2">수량</th>
              <th className="text-right px-3 py-2">단가</th>
              <th className="text-right px-3 py-2">금액</th>
              <th className="text-left px-3 py-2">출발 → 도착</th>
              <th className="text-left px-3 py-2">이동자</th>
              <th className="text-left px-3 py-2">메모</th>
            </tr>
          </thead>
          <tbody className="tabular-nums">
            {rows.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-12 text-slate-400">
                {loading ? "조회 중..." : "이동 내역이 없습니다."}
              </td></tr>
            ) : rows.map((r) => (
              <tr key={r.OBJID} className="border-t border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-2 text-xs font-mono">{r.MOVED_AT}</td>
                <td className="px-3 py-2">
                  <div className="font-semibold">{r.ITEM_NAME}</div>
                  <div className="text-[10px] text-slate-400">{r.ITEM_CODE}</div>
                </td>
                <td className="px-3 py-2 text-right font-semibold">{fmt(Number(r.QTY))} {r.UNIT}</td>
                <td className="px-3 py-2 text-right text-slate-500">{fmt(Number(r.COST_PRICE))}</td>
                <td className="px-3 py-2 text-right font-bold text-sky-700">₩{fmt(Number(r.AMOUNT))}</td>
                <td className="px-3 py-2 text-xs">
                  <span className="text-slate-700">{r.FROM_WH}</span>
                  <span className="text-slate-300 mx-1">→</span>
                  <span className="text-emerald-700 font-semibold">{r.TO_WH}</span>
                </td>
                <td className="px-3 py-2 text-xs">
                  <div className="font-semibold">{r.REG_USER_NAME ?? "-"}</div>
                  <div className="text-[10px] text-slate-400 font-mono">{r.REGID}</div>
                </td>
                <td className="px-3 py-2 text-[10px] text-slate-500 max-w-[200px] truncate" title={r.MEMO ?? ""}>
                  {r.MEMO ?? ""}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
