"use client";

import { useCallback, useEffect, useState } from "react";
import { AlertTriangle, AlertCircle, Clock, RefreshCcw } from "lucide-react";

interface Row {
  INBOUND_OBJID: string; INBOUND_NO: string;
  INBOUND_DATE: string; EXPIRY_DATE: string; DAYS_LEFT: number;
  WH_NAME: string | null; VENDOR_NAME: string | null;
  COMPLETED_BY: string | null; MEMO: string | null; TOTAL_AMOUNT: number;
}

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

export default function ExpiryAlertsPage() {
  const [days, setDays] = useState(30);
  const [rows, setRows] = useState<Row[]>([]);
  const [counts, setCounts] = useState({ expired: 0, urgent: 0, soon: 0 });
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/admin/expiry-alerts", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ days }),
      });
      const j = await res.json();
      setRows(j.RESULTLIST ?? []);
      setCounts({ expired: j.EXPIRED_CNT ?? 0, urgent: j.URGENT_CNT ?? 0, soon: j.SOON_CNT ?? 0 });
    } finally { setLoading(false); }
  }, [days]);

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

  const rowStyle = (daysLeft: number) => {
    if (daysLeft < 0) return "bg-rose-50 border-l-4 border-l-rose-500";
    if (daysLeft <= 7) return "bg-amber-50 border-l-4 border-l-amber-500";
    return "bg-white";
  };
  const badge = (daysLeft: number) => {
    if (daysLeft < 0) return <span className="text-[10px] px-1.5 py-0.5 rounded bg-rose-100 text-rose-700 font-bold">만료 {Math.abs(daysLeft)}일 경과</span>;
    if (daysLeft === 0) return <span className="text-[10px] px-1.5 py-0.5 rounded bg-rose-100 text-rose-700 font-bold">오늘 만료</span>;
    if (daysLeft <= 7) return <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 font-bold">D-{daysLeft}</span>;
    return <span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">D-{daysLeft}</span>;
  };

  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">
            <AlertTriangle size={20} className="text-amber-600" />
            유통기한 임박 알림
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            입고 시 입력한 소비기한 기준. 만료 / D-7 이내 / D-30 이내 분류. 관리자 그룹 전용.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <select value={days} onChange={(e) => setDays(Number(e.target.value))}
            className="h-9 px-3 rounded border border-slate-300 bg-white text-sm">
            <option value={7}>7일 이내</option>
            <option value={14}>14일 이내</option>
            <option value={30}>30일 이내</option>
            <option value={60}>60일 이내</option>
            <option value={90}>90일 이내</option>
          </select>
          <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>
        </div>
      </div>

      {/* 알림 카드 */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-rose-50 border border-rose-200 rounded-xl p-4">
          <div className="text-[11px] text-rose-700 font-semibold mb-1 flex items-center gap-1">
            <AlertCircle size={14} /> 이미 만료
          </div>
          <div className="text-2xl font-bold text-rose-700 tabular-nums">{counts.expired}건</div>
        </div>
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="text-[11px] text-amber-700 font-semibold mb-1 flex items-center gap-1">
            <AlertTriangle size={14} /> 7일 이내 임박
          </div>
          <div className="text-2xl font-bold text-amber-700 tabular-nums">{counts.urgent}건</div>
        </div>
        <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-600 font-semibold mb-1 flex items-center gap-1">
            <Clock size={14} /> 30일 이내 주의
          </div>
          <div className="text-2xl font-bold text-slate-700 tabular-nums">{counts.soon}건</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">
            <tr>
              <th className="text-left px-3 py-2">입고번호</th>
              <th className="text-left px-3 py-2">소비기한</th>
              <th className="text-center 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>
              <th className="text-left px-3 py-2">메모</th>
              <th className="text-right 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.INBOUND_OBJID} className={`border-t border-slate-100 ${rowStyle(Number(r.DAYS_LEFT))}`}>
                <td className="px-3 py-2 font-semibold">{r.INBOUND_NO}
                  <div className="text-[10px] text-slate-400">입고 {r.INBOUND_DATE}</div></td>
                <td className="px-3 py-2 font-mono">{r.EXPIRY_DATE}</td>
                <td className="px-3 py-2 text-center">{badge(Number(r.DAYS_LEFT))}</td>
                <td className="px-3 py-2">{r.WH_NAME ?? "-"}</td>
                <td className="px-3 py-2">{r.VENDOR_NAME ?? "-"}</td>
                <td className="px-3 py-2 text-xs">{r.COMPLETED_BY ?? "-"}</td>
                <td className="px-3 py-2 text-[10px] text-slate-500 whitespace-pre-line max-w-[300px] truncate" title={r.MEMO ?? ""}>
                  {r.MEMO ?? ""}
                </td>
                <td className="px-3 py-2 text-right font-semibold">₩{fmt(Number(r.TOTAL_AMOUNT))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
