"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ShoppingCart, Package, ClipboardList, TrendingUp, AlertTriangle, ArrowRight } from "lucide-react";

type DashboardData =
  | { summary: { REQUESTED_CNT: number; PROGRESS_CNT: number; MONTH_AMOUNT: number; UNPAID: number } | null;
      recent: Array<{ OBJID: string; ORDER_NO: string; ORDER_DATE: string; STATUS: string; TOTAL_AMOUNT: number }>; }
  | { summary: { PENDING_CNT: number; TODAY_CNT: number; MONTH_AMOUNT: number; UNPAID: number } | null;
      lowStock: Array<{ OBJID: string; ITEM_CODE: string; ITEM_NAME: string; STOCK_QTY: number }>;
      daily: Array<{ DAY: string; CNT: number; AMOUNT: number }>;
      pending: Array<{ OBJID: string; ORDER_NO: string; COMPANY_NAME: string; ORDER_DATE: string; TOTAL_AMOUNT: number }>; };

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const pad = (n: number) => String(n).padStart(2, "0");
const todayISO = () => { const d = new Date(); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; };
const firstOfMonthISO = () => { const d = new Date(); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-01`; };
const STATUS_LABEL: Record<string, string> = {
  REQUESTED: "출고요청", APPROVED: "출고완료",
  PAID: "입금완료", INVOICED: "계산서발행", CANCELLED: "취소",
};
const STATUS_COLOR: Record<string, string> = {
  REQUESTED: "bg-amber-100 text-amber-700",
  APPROVED: "bg-blue-100 text-blue-700",
  INVOICED: "bg-violet-100 text-violet-700",
  PAID: "bg-emerald-100 text-emerald-700",
  CANCELLED: "bg-slate-100 text-slate-500",
};

export default function MomoDashboard() {
  const router = useRouter();
  const [role, setRole] = useState<"USER" | "ADMIN" | null>(null);
  const [data, setData] = useState<DashboardData | null>(null);

  useEffect(() => {
    fetch("/api/auth/me").then((r) => r.json()).then((d) => {
      const u = d?.user;
      const isAdmin = u?.role === "ADMIN" || u?.isAdmin === true || u?.userType === "A";
      if (!isAdmin) {
        // 일반 구매자는 대시보드 대상이 아님 → 출고 요청 화면으로 즉시 이동
        router.replace("/m/orders/new");
        return;
      }
      setRole("ADMIN");
      fetch("/api/m/dashboard").then((r) => r.json()).then(setData);
    });
  }, [router]);

  if (role !== "ADMIN" || !data) return <div className="text-slate-500">불러오는 중...</div>;

  // ADMIN 전용
  const d = data as Extract<DashboardData, { lowStock: unknown[] }>;
  const s = d.summary ?? { PENDING_CNT: 0, TODAY_CNT: 0, MONTH_AMOUNT: 0, UNPAID: 0 };
  const maxAmt = Math.max(1, ...d.daily.map((x) => Number(x.AMOUNT)));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">관리자 대시보드</h1>
        <p className="text-slate-500 text-sm mt-1">전체 발주 · 매출 · 재고 현황입니다.</p>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card title="승인 대기" value={s.PENDING_CNT} suffix="건" tone="amber" icon={<ClipboardList size={18} />}
          href="/m/admin/orders?status=REQUESTED&dateFrom=&dateTo=" />
        <Card title="오늘 발주" value={s.TODAY_CNT} suffix="건" tone="blue" icon={<ShoppingCart size={18} />}
          href={`/m/admin/orders?dateFrom=${todayISO()}&dateTo=${todayISO()}`} />
        <Card title="이번달 매출" value={fmt(s.MONTH_AMOUNT)} prefix="₩" tone="emerald" icon={<TrendingUp size={18} />}
          href={`/m/admin/orders?dateFrom=${firstOfMonthISO()}&dateTo=${todayISO()}`} />
        <Card title="미수금" value={fmt(s.UNPAID)} prefix="₩" tone="rose" icon={<AlertTriangle size={18} />}
          href="/m/admin/payments" />
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <Section title="최근 14일 발주 매출">
          <div className="flex items-end gap-1.5 h-40 px-2 pt-2">
            {d.daily.length === 0 ? (
              <div className="text-slate-400 text-sm m-auto">데이터가 없습니다.</div>
            ) : (
              d.daily.map((x, i) => (
                <div key={i} className="flex-1 flex flex-col items-center gap-1 min-w-0">
                  <div className="w-full bg-emerald-500/80 rounded-t hover:bg-emerald-600 transition" style={{ height: `${Math.max(2, (Number(x.AMOUNT) / maxAmt) * 100)}%` }} title={`₩${fmt(x.AMOUNT)}`} />
                  <div className="text-[10px] text-slate-500 -rotate-45 origin-top-left mt-1 whitespace-nowrap">{x.DAY}</div>
                </div>
              ))
            )}
          </div>
        </Section>

        <Section title="재고 부족 (10개 미만)">
          <DataTable
            empty="재고 부족 품목이 없습니다."
            cols={[
              { k: "ITEM_CODE", t: "품목코드" },
              { k: "ITEM_NAME", t: "품목명" },
              { k: "STOCK_QTY", t: "현재고", align: "right", render: (v: number) => <span className="text-rose-600 font-bold">{fmt(v)}</span> },
            ]}
            rows={d.lowStock}
          />
        </Section>
      </div>

      <Section title="승인 대기 발주" linkHref="/m/admin/orders" linkLabel="발주 관리로 이동">
        <DataTable
          empty="승인 대기 발주가 없습니다."
          cols={[
            { k: "ORDER_NO", t: "발주번호" },
            { k: "COMPANY_NAME", t: "업체명" },
            { k: "ORDER_DATE", t: "발주일" },
            { k: "TOTAL_AMOUNT", t: "합계", align: "right", render: (v: number) => `₩${fmt(v)}` },
          ]}
          rows={d.pending}
        />
      </Section>
    </div>
  );
}

function Card({ title, value, suffix, prefix, tone, icon, href }: { title: string; value: number | string; suffix?: string; prefix?: string; tone: "amber" | "blue" | "emerald" | "rose"; icon?: React.ReactNode; href?: string }) {
  const toneCls = {
    amber: "from-amber-50 to-amber-100 text-amber-800 border-amber-200",
    blue: "from-blue-50 to-blue-100 text-blue-800 border-blue-200",
    emerald: "from-emerald-50 to-emerald-100 text-emerald-800 border-emerald-200",
    rose: "from-rose-50 to-rose-100 text-rose-800 border-rose-200",
  }[tone];
  const inner = (
    <>
      <div className="flex items-center justify-between mb-1">
        <div className="text-xs font-semibold opacity-80">{title}</div>
        {icon}
      </div>
      <div className="text-2xl font-bold tabular-nums">
        {prefix}{value}{suffix && <span className="text-sm font-semibold ml-1">{suffix}</span>}
      </div>
    </>
  );
  const className = `rounded-xl border bg-gradient-to-br ${toneCls} p-5 ${href ? "cursor-pointer hover:-translate-y-0.5 hover:shadow-md transition" : ""}`;
  if (href) {
    return <Link href={href} className={className}>{inner}</Link>;
  }
  return <div className={className}>{inner}</div>;
}

function Section({ title, children, linkHref, linkLabel }: { title: string; children: React.ReactNode; linkHref?: string; linkLabel?: string }) {
  return (
    <div className="bg-white border border-slate-200 rounded-xl p-5 shadow-sm">
      <div className="flex items-center justify-between mb-3">
        <h3 className="font-bold text-slate-800">{title}</h3>
        {linkHref && (
          <Link href={linkHref} className="text-xs text-emerald-700 font-semibold hover:underline">
            {linkLabel} →
          </Link>
        )}
      </div>
      {children}
    </div>
  );
}

interface Col { k: string; t: string; align?: "left" | "right" | "center"; render?: (v: any, row: any) => React.ReactNode } // eslint-disable-line @typescript-eslint/no-explicit-any
function DataTable({ cols, rows, empty }: { cols: Col[]; rows: Array<Record<string, unknown>>; empty: string }) {
  if (!rows || rows.length === 0) return <div className="text-slate-400 text-sm py-8 text-center">{empty}</div>;
  return (
    <table className="w-full text-sm">
      <thead>
        <tr className="text-slate-500 border-b border-slate-100">
          {cols.map((c) => (
            <th key={c.k} className={`pb-2 font-semibold text-${c.align ?? "left"} text-xs`}>{c.t}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i} className="border-b border-slate-50 last:border-0">
            {cols.map((c) => (
              <td key={c.k} className={`py-2.5 text-${c.align ?? "left"}`}>
                {c.render ? c.render(r[c.k], r) : String(r[c.k] ?? "")}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}
