"use client";

import { useEffect, useState } from "react";
import { Trophy } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, EmptyState, Skeleton } from "@/components/ui";

type Row = { name: string; email: string; sales: number; revenue: number; earnings: number };

const inr = (n: number) => "₹" + n.toLocaleString("en-IN");
const MEDAL = ["#F59E0B", "#9CA3AF", "#B45309"];

export default function LeaderboardPage() {
  const [rows, setRows] = useState<Row[] | null>(null);

  useEffect(() => {
    api.get("/admin/leaderboard").then(setRows).catch(() => setRows([]));
  }, []);

  return (
    <div>
      <PageHeader title="Leaderboard" subtitle="Top affiliates by earnings" />

      {!rows ? (
        <Skeleton className="h-72" />
      ) : rows.length === 0 ? (
        <Card><EmptyState icon={<Trophy className="h-6 w-6" />} title="No earnings yet" description="Your top performers will show up here once sales come in." /></Card>
      ) : (
        <Card className="!p-0">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[560px] text-left text-sm">
              <thead className="bg-gray-50 text-xs uppercase tracking-wide text-gray-500">
                <tr>
                  <th className="px-4 py-2.5 font-medium">Rank</th>
                  <th className="font-medium">Affiliate</th>
                  <th className="px-4 text-right font-medium">Sales</th>
                  <th className="px-4 text-right font-medium">Revenue</th>
                  <th className="px-4 text-right font-medium">Earnings</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {rows.map((r, i) => (
                  <tr key={r.email || i} className={i < 3 ? "bg-amber-50/30" : ""}>
                    <td className="px-4 py-3">
                      <span
                        className="inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold text-white"
                        style={{ backgroundColor: i < 3 ? MEDAL[i] : "#CBD5E1" }}
                      >
                        {i + 1}
                      </span>
                    </td>
                    <td>
                      <div className="font-medium text-gray-900">{r.name}</div>
                      <div className="text-xs text-gray-400">{r.email}</div>
                    </td>
                    <td className="px-4 text-right">{r.sales}</td>
                    <td className="px-4 text-right text-gray-600">{inr(r.revenue)}</td>
                    <td className="px-4 text-right font-semibold text-green-700">{inr(r.earnings)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  );
}
