"use client";

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

interface Wh { OBJID: string; WH_CODE: string; WH_NAME: string }
interface ItemRow {
  OBJID: string;
  ITEM_CODE: string;
  ITEM_NAME: string;
  UNIT: string;
  UNIT_PRICE: string | number;
  IS_TAX_FREE: string;
  SALE_START_DATE: string | null;
  SALE_END_DATE: string | null;
  VENDOR_NAME: string | null;
  STOCK: Record<string, number>;  // wh_code → 현재고
  ORDER: Record<string, number>;  // wh_code → 발주수량
  TOTAL_STOCK: number;
  TOTAL_ORDER: number;
}

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const today = () => new Date().toISOString().slice(0, 10);

export default function DailyOrderInventoryPage() {
  const [targetDate, setTargetDate] = useState<string>(today());
  const [keyword, setKeyword] = useState("");
  const [warehouses, setWarehouses] = useState<Wh[]>([]);
  const [items, setItems] = useState<ItemRow[]>([]);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/admin/daily-order-inventory", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ targetDate, keyword }),
      });
      if (res.ok) {
        const j = await res.json();
        setWarehouses(j.WAREHOUSES ?? []);
        setItems(j.ITEMS ?? []);
      } else {
        setWarehouses([]);
        setItems([]);
      }
    } finally {
      setLoading(false);
    }
  }, [targetDate, keyword]);

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

  const totalOrderQty = items.reduce((a, r) => a + Number(r.TOTAL_ORDER || 0), 0);
  const totalStockQty = items.reduce((a, r) => a + Number(r.TOTAL_STOCK || 0), 0);

  const onExport = () => {
    if (items.length === 0 || warehouses.length === 0) return;
    type Row = Record<string, string | number>;
    const data: Row[] = [];
    for (const w of warehouses) {
      const orderRow: Row = { WH: `${w.WH_NAME} (${w.WH_CODE})`, KIND: "발주수량" };
      const stockRow: Row = { WH: `${w.WH_NAME} (${w.WH_CODE})`, KIND: "재고수량" };
      for (const it of items) {
        orderRow[it.ITEM_NAME] = Number(it.ORDER[w.WH_CODE] ?? 0);
        stockRow[it.ITEM_NAME] = Number(it.STOCK[w.WH_CODE] ?? 0);
      }
      data.push(orderRow, stockRow);
    }
    const cols = [
      { header: "창고", key: "WH" },
      { header: "분류", key: "KIND" },
      ...items.map((it) => ({ header: it.ITEM_NAME, key: it.ITEM_NAME })),
    ];
    downloadXlsx(`일자별발주재고_${targetDate}`, data, cols);
  };

  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">
            <CalendarDays size={20} className="text-emerald-700" />
            일자별 발주/재고 현황
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            선택일에 <b>판매 가능</b>한 품목을 헤더로, 각 창고를 좌측에 배치한 매트릭스.
            발주수량 = 그 날짜의 발주(REQUESTED는 거래처 default 창고로 가상 배정 / APPROVED 이후는 출고 창고). 재고수량 = 해당 창고 현재고.
          </p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <input
            type="date"
            value={targetDate}
            onChange={(e) => setTargetDate(e.target.value)}
            className="h-9 px-3 rounded border border-slate-300 text-sm"
          />
          <button
            onClick={() => setTargetDate(today())}
            className="h-9 px-3 rounded border border-slate-300 bg-white text-slate-700 text-xs font-semibold"
          >
            오늘
          </button>
          <div className="relative">
            <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400" />
            <input
              type="text"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") load(); }}
              placeholder="품목명/코드"
              className="h-9 pl-8 pr-3 rounded border border-slate-300 text-sm w-48"
            />
          </div>
          <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={items.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-40"
          >
            <Download size={14} /> 엑셀
          </button>
        </div>
      </div>

      {/* 요약 카드 */}
      <div className="grid grid-cols-3 sm:grid-cols-3 gap-3">
        <SummaryCard label="판매가능 품목" value={`${fmt(items.length)} 종`} color="slate" />
        <SummaryCard label="발주수량 합계" value={`${fmt(totalOrderQty)}`} color="rose" />
        <SummaryCard label="재고수량 합계" value={`${fmt(totalStockQty)}`} color="emerald" />
      </div>

      {/* 매트릭스: 헤더=품목, 행=창고 */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="text-sm border-collapse">
          <thead className="bg-slate-50 text-slate-600 sticky top-0">
            <tr>
              <th className="text-left px-3 py-2 border-b border-slate-200 sticky left-0 bg-slate-50 z-10 min-w-[120px]">창고</th>
              <th className="text-center px-3 py-2 border-b border-slate-200 sticky left-[120px] bg-slate-50 z-10 min-w-[90px]">분류</th>
              {items.map((it) => (
                <th key={it.OBJID} className="text-right px-3 py-2 border-b border-slate-200 min-w-[110px] whitespace-nowrap">
                  <div>{it.ITEM_NAME}</div>
                  <div className="text-[10px] text-slate-400 font-mono font-normal">{it.ITEM_CODE}</div>
                  {it.SALE_END_DATE && (
                    <div className="text-[10px] text-rose-600 font-semibold tabular-nums">~ {it.SALE_END_DATE}</div>
                  )}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="tabular-nums">
            {items.length === 0 || warehouses.length === 0 ? (
              <tr>
                <td colSpan={2 + items.length} className="text-center py-12 text-slate-400">
                  {loading ? "조회 중..." : "데이터가 없습니다."}
                </td>
              </tr>
            ) : [
              /* 전체 합계 — 모든 창고의 발주수량/재고수량 합 (상단 강조 행) */
              <tr key="__total-order" className="bg-emerald-50/70 border-y-2 border-emerald-300 font-bold">
                <td className="px-3 py-2 align-top sticky left-0 bg-emerald-50/70" rowSpan={2}>
                  <div className="text-emerald-800">전체 합계</div>
                  <div className="text-[10px] text-emerald-600 font-normal">모든 창고</div>
                </td>
                <td className="px-3 py-1.5 text-center text-[11px] text-rose-700 bg-rose-50/60 sticky left-[120px]">발주수량</td>
                {items.map((it) => {
                  const v = Number(it.TOTAL_ORDER || 0);
                  return (
                    <td key={it.OBJID} className={`px-3 py-1.5 text-right ${v === 0 ? "text-slate-300" : "text-rose-700"}`}>
                      {v === 0 ? "-" : fmt(v)}
                    </td>
                  );
                })}
              </tr>,
              <tr key="__total-stock" className="bg-emerald-50/70 border-b-2 border-emerald-300 font-bold">
                <td className="px-3 py-1.5 text-center text-[11px] text-emerald-700 bg-emerald-100/60 sticky left-[120px]">재고수량</td>
                {items.map((it) => {
                  const v = Number(it.TOTAL_STOCK || 0);
                  const negative = v < 0;
                  return (
                    <td key={it.OBJID} className={`px-3 py-1.5 text-right ${negative ? "text-rose-600" : v === 0 ? "text-slate-300" : "text-emerald-700"}`}>
                      {v === 0 ? "-" : fmt(v)}
                    </td>
                  );
                })}
              </tr>,
              /* 창고별 — 각 창고 발주수량/재고수량 두 줄 */
              ...warehouses.flatMap((w) => [
                <tr key={`${w.WH_CODE}-order`} className="border-t border-slate-100 hover:bg-slate-50/60">
                  <td className="px-3 py-2 align-top font-semibold sticky left-0 bg-white" rowSpan={2}>
                    {w.WH_NAME}
                    <div className="text-[10px] text-slate-400 font-mono">{w.WH_CODE}</div>
                  </td>
                  <td className="px-3 py-1.5 text-center text-[11px] text-rose-700 bg-rose-50/40 sticky left-[120px]">발주수량</td>
                  {items.map((it) => {
                    const v = Number(it.ORDER[w.WH_CODE] ?? 0);
                    return (
                      <td key={it.OBJID} className={`px-3 py-1.5 text-right ${v === 0 ? "text-slate-300" : "text-rose-700 font-semibold"}`}>
                        {v === 0 ? "-" : fmt(v)}
                      </td>
                    );
                  })}
                </tr>,
                <tr key={`${w.WH_CODE}-stock`} className="border-b border-slate-100">
                  <td className="px-3 py-1.5 text-center text-[11px] text-emerald-700 bg-emerald-50/40 font-semibold sticky left-[120px]">재고수량</td>
                  {items.map((it) => {
                    const v = Number(it.STOCK[w.WH_CODE] ?? 0);
                    const negative = v < 0;
                    return (
                      <td key={it.OBJID} className={`px-3 py-1.5 text-right ${negative ? "text-rose-600 font-bold" : v === 0 ? "text-slate-300" : "text-emerald-700 font-semibold"}`}>
                        {v === 0 ? "-" : fmt(v)}
                      </td>
                    );
                  })}
                </tr>,
              ]),
            ]}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SummaryCard({ label, value, color }: { label: string; value: string; color: "slate" | "rose" | "emerald" }) {
  const cls = {
    slate:   "bg-slate-50   border-slate-200   text-slate-800",
    rose:    "bg-rose-50    border-rose-200    text-rose-800",
    emerald: "bg-emerald-50 border-emerald-200 text-emerald-800",
  }[color];
  return (
    <div className={`rounded-xl border ${cls} p-4`}>
      <div className="text-xs font-semibold opacity-80 mb-1">{label}</div>
      <div className="text-lg sm:text-xl font-bold tabular-nums">{value}</div>
    </div>
  );
}
