import { useEffect, useState, type ReactNode } from "react";
import { adminFetch } from "./adminApi";
import PageHeader, { LoadingBlock } from "./PageHeader";

type MetricBlock = { total: number; today: number; thisWeek: number; thisMonth: number };
type DashboardData = {
  users: MetricBlock;
  collections: MetricBlock;
  redemptions: MetricBlock;
};

type CardSpec = {
  key: keyof DashboardData;
  eyebrow: string;
  label: string;
  caption: string;
  accent: string;
  icon: ReactNode;
};

const CARDS: CardSpec[] = [
  {
    key: "users",
    eyebrow: "Users",
    label: "注册用户",
    caption: "累计参与城市漫步的旅人",
    accent: "var(--jade)",
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
        <circle cx="9" cy="7" r="4" />
        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" />
      </svg>
    ),
  },
  {
    key: "collections",
    eyebrow: "Collected",
    label: "图章收集",
    caption: "触发一次 NFC 即记一次",
    accent: "var(--gold)",
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <circle cx="12" cy="12" r="9" />
        <path d="M12 3a9 9 0 010 18M12 3v18M3 12h18" />
      </svg>
    ),
  },
  {
    key: "redemptions",
    eyebrow: "Redeemed",
    label: "兑换次数",
    caption: "访客将图章兑换为奖品",
    accent: "var(--terracotta)",
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <path d="M20 12v10H4V12M2 7h20v5H2zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z" />
      </svg>
    ),
  },
];

export default function Dashboard() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch<DashboardData>("/dashboard")
      .then(setData)
      .finally(() => setLoading(false));
  }, []);

  return (
    <>
      <PageHeader
        eyebrow="01 · Dashboard"
        title="数据看板"
        caption={`截至 ${new Date().toLocaleString("zh-CN", { dateStyle: "long", timeStyle: "short" })}（Asia/Shanghai）`}
      />

      {loading || !data ? (
        <LoadingBlock />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
          {CARDS.map((card, i) => (
            <MetricCard key={card.key} card={card} metric={data[card.key]} index={i} />
          ))}
        </div>
      )}
    </>
  );
}

function MetricCard({ card, metric, index }: { card: CardSpec; metric: MetricBlock; index: number }) {
  return (
    <div
      className="relative rounded-2xl bg-white/85 border border-[var(--border-muted)] overflow-hidden animate-admin-row"
      style={{
        animationDelay: `${index * 0.08}s`,
        boxShadow: "0 1px 2px rgba(16,16,30,0.04), 0 12px 32px rgba(16,16,30,0.05)",
      }}
    >
      <span
        className="absolute top-0 left-0 right-0 h-0.5"
        style={{ backgroundColor: card.accent }}
      />

      {/* Header: eyebrow + icon */}
      <div className="px-7 pt-6 pb-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="block w-5 h-px" style={{ backgroundColor: card.accent, opacity: 0.6 }} />
          <span
            className="text-[10px] tracking-[0.32em] uppercase"
            style={{ fontFamily: "'Playfair Display', serif", fontWeight: 500, color: card.accent }}
          >
            {card.eyebrow}
          </span>
        </div>
        <span style={{ color: card.accent, opacity: 0.6 }}>{card.icon}</span>
      </div>

      {/* Total */}
      <div className="px-7 pb-5">
        <p
          className="text-[64px] leading-none text-[var(--text-primary)]"
          style={{ fontFamily: "'Playfair Display', serif", fontWeight: 600, letterSpacing: "-0.03em" }}
        >
          {metric.total}
        </p>
        <div className="mt-2 flex items-baseline gap-2">
          <span className="text-sm font-medium text-[var(--text-primary)]">{card.label}</span>
          <span className="text-[10px] tracking-[0.2em] uppercase text-[var(--text-muted)]">Total</span>
        </div>
        <p className="mt-1 text-[11px] text-[var(--text-muted)] leading-relaxed">{card.caption}</p>
      </div>

      {/* Time-slice metrics */}
      <div className="grid grid-cols-3 divide-x divide-[var(--border-muted)] border-t border-[var(--border-muted)] bg-[var(--bg-paper)]/40">
        <SliceCell label="Today" value={metric.today} labelCn="今日" accent={card.accent} />
        <SliceCell label="Week" value={metric.thisWeek} labelCn="本周" accent={card.accent} />
        <SliceCell label="Month" value={metric.thisMonth} labelCn="本月" accent={card.accent} />
      </div>
    </div>
  );
}

function SliceCell({
  label,
  labelCn,
  value,
  accent,
}: {
  label: string;
  labelCn: string;
  value: number;
  accent: string;
}) {
  const isZero = value === 0;
  return (
    <div className="px-4 py-4 text-center">
      <div
        className="text-[9px] tracking-[0.3em] uppercase mb-1"
        style={{ fontFamily: "'Playfair Display', serif", color: accent, opacity: 0.7 }}
      >
        {label}
      </div>
      <div
        className="text-xl leading-none"
        style={{
          fontFamily: "'Playfair Display', serif",
          fontWeight: 600,
          color: isZero ? "var(--text-muted)" : "var(--text-primary)",
          letterSpacing: "-0.01em",
        }}
      >
        {isZero ? "0" : `+${value}`}
      </div>
      <div className="text-[10px] text-[var(--text-muted)] mt-1">{labelCn}</div>
    </div>
  );
}
