import { useState, useEffect } from "react";
import { adminFetch } from "./adminApi";
import PageHeader, { LoadingBlock } from "./PageHeader";
import { TableCard, TableHeadRow } from "./StampList";

type RedemptionRecord = {
  id: string;
  userId: string;
  stampCount: number;
  redeemedAt: string;
  user: { username: string; phone: string };
  rule: { name: string };
};

type Stats = {
  userCount: number;
  collectionCount: number;
  redemptionCount: number;
};

const STAT_CARDS: { key: keyof Stats; label: string; eyebrow: string; accent: string }[] = [
  { key: "userCount", label: "注册用户", eyebrow: "Users", accent: "var(--jade)" },
  { key: "collectionCount", label: "当前收集数", eyebrow: "Collected", accent: "var(--gold)" },
  { key: "redemptionCount", label: "累计兑换", eyebrow: "Redeemed", accent: "var(--terracotta)" },
];

export default function RedemptionLog() {
  const [records, setRecords] = useState<RedemptionRecord[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      adminFetch<RedemptionRecord[]>("/redemptions"),
      adminFetch<Stats>("/stats"),
    ])
      .then(([recs, st]) => {
        setRecords(recs);
        setStats(st);
      })
      .finally(() => setLoading(false));
  }, []);

  return (
    <>
      <PageHeader
        eyebrow="07 · Log"
        title="兑换记录"
        caption="账户、图章收集与兑换的完整轨迹"
      />

      {loading ? (
        <LoadingBlock />
      ) : (
        <>
          {/* Stats */}
          {stats && (
            <div className="grid grid-cols-3 gap-5 mb-8">
              {STAT_CARDS.map((card, i) => (
                <div
                  key={card.key}
                  className="relative rounded-2xl bg-white/80 border border-[var(--border-muted)] p-6 overflow-hidden animate-admin-row"
                  style={{
                    animationDelay: `${i * 0.08}s`,
                    boxShadow: "0 1px 2px rgba(16,16,30,0.04), 0 8px 24px rgba(16,16,30,0.04)",
                  }}
                >
                  <span
                    className="absolute top-0 left-0 right-0 h-0.5"
                    style={{ backgroundColor: card.accent }}
                  />
                  <div className="flex items-center gap-2 mb-3">
                    <span className="block w-4 h-px" style={{ backgroundColor: card.accent, opacity: 0.7 }} />
                    <span
                      className="text-[10px] tracking-[0.3em] uppercase"
                      style={{
                        fontFamily: "'Playfair Display', serif",
                        fontWeight: 500,
                        color: card.accent,
                      }}
                    >
                      {card.eyebrow}
                    </span>
                  </div>
                  <p
                    className="text-[44px] leading-none text-[var(--text-primary)]"
                    style={{ fontFamily: "'Playfair Display', serif", fontWeight: 600, letterSpacing: "-0.02em" }}
                  >
                    {stats[card.key]}
                  </p>
                  <p className="text-sm text-[var(--text-secondary)] mt-2">{card.label}</p>
                </div>
              ))}
            </div>
          )}

          {/* Records */}
          <div className="flex items-center gap-3 mb-4">
            <span className="block w-5 h-px bg-[var(--gold)]/40" />
            <span
              className="text-[10px] tracking-[0.3em] uppercase text-[var(--text-muted)]"
              style={{ fontFamily: "'Playfair Display', serif" }}
            >
              Ledger
            </span>
          </div>

          <TableCard>
            {records.length === 0 ? (
              <div className="py-16 flex flex-col items-center gap-3">
                <div className="w-14 h-14 rounded-full flex items-center justify-center bg-[var(--bg-paper)]">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--gold)" strokeWidth="1.6">
                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
                    <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" />
                  </svg>
                </div>
                <p className="text-sm text-[var(--text-muted)]">暂无兑换记录</p>
              </div>
            ) : (
              <table className="w-full">
                <thead>
                  <TableHeadRow cols={["用户", "手机号", "兑换奖品", "扣除枚数", "时间"]} />
                </thead>
                <tbody>
                  {records.map((r, i) => (
                    <tr
                      key={r.id}
                      className="border-t border-[var(--border-muted)] hover:bg-white/60 transition-colors animate-admin-row"
                      style={{ animationDelay: `${Math.min(i, 12) * 0.03}s` }}
                    >
                      <td className="px-5 py-4">
                        <span className="text-[15px] font-medium text-[var(--text-primary)]">
                          {r.user.username}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        <span className="text-sm text-[var(--text-secondary)] font-mono">{r.user.phone}</span>
                      </td>
                      <td className="px-5 py-4">
                        <span className="text-sm text-[var(--text-secondary)]">{r.rule.name}</span>
                      </td>
                      <td className="px-5 py-4 text-center w-[140px]">
                        <span
                          className="inline-flex items-baseline gap-1 text-[var(--terracotta)]"
                          style={{ fontFamily: "'Playfair Display', serif" }}
                        >
                          <span className="text-xl font-semibold leading-none">−{r.stampCount}</span>
                          <span className="text-[10px] tracking-[0.2em] uppercase opacity-70">枚</span>
                        </span>
                      </td>
                      <td className="px-5 py-4 text-right w-[200px]">
                        <span className="text-xs text-[var(--text-muted)] font-mono">
                          {new Date(r.redeemedAt).toLocaleString("zh-CN")}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </TableCard>
        </>
      )}
    </>
  );
}
