'use client';

import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';

interface LeaderboardEntry {
  rank: number;
  name: string;
  avatar: string;
  conversations: number;
  bookingRate: number;
  csatScore: number;
}

function RankBadge({ rank }: { rank: number }) {
  const colors: Record<number, string> = {
    1: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/30',
    2: 'bg-slate-400/15 text-slate-300 border-slate-400/30',
    3: 'bg-amber-600/15 text-amber-500 border-amber-600/30',
  };

  return (
    <div
      className={cn(
        'flex h-7 w-7 items-center justify-center rounded-lg border text-xs font-bold',
        colors[rank] || 'bg-slate-700/30 text-slate-500 border-slate-700/30'
      )}
    >
      {rank}
    </div>
  );
}

function CsatBar({ score }: { score: number }) {
  const pct = (score / 5) * 100;
  const color =
    score >= 4.5
      ? 'bg-emerald-500'
      : score >= 4.0
      ? 'bg-cyan-500'
      : score >= 3.5
      ? 'bg-yellow-500'
      : 'bg-rose-500';

  return (
    <div className="flex items-center gap-2">
      <div className="h-1.5 w-16 rounded-full bg-slate-700/50 overflow-hidden">
        <div className={cn('h-full rounded-full transition-all', color)} style={{ width: `${pct}%` }} />
      </div>
      <span className="text-sm font-medium text-white">{score.toFixed(1)}</span>
    </div>
  );
}

export default function BotLeaderboard() {
  const [data, setData] = useState<LeaderboardEntry[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/analytics/leaderboard')
      .then((r) => r.json())
      .then((d) => setData(d.leaderboard || []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="rounded-xl border border-slate-700/40 bg-[#0f1729]/80 overflow-hidden">
      <div className="px-6 py-5 border-b border-slate-700/30">
        <h3 className="text-base font-semibold text-white">Top Performing Bots</h3>
        <p className="text-xs text-slate-500 mt-0.5">Ranked by overall performance score</p>
      </div>

      {loading ? (
        <div className="p-8 flex items-center justify-center">
          <div className="h-8 w-8 border-2 border-cyan-500/30 border-t-cyan-500 rounded-full animate-spin" />
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-700/20">
                <th className="px-6 py-3 text-left text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                  Rank
                </th>
                <th className="px-6 py-3 text-left text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                  Bot Name
                </th>
                <th className="px-6 py-3 text-right text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                  Conversations
                </th>
                <th className="px-6 py-3 text-right text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                  Booking Rate
                </th>
                <th className="px-6 py-3 text-left text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                  CSAT Score
                </th>
              </tr>
            </thead>
            <tbody>
              {data.map((bot) => (
                <tr
                  key={bot.rank}
                  className="border-b border-slate-700/10 transition-colors hover:bg-slate-800/20"
                >
                  <td className="px-6 py-3.5">
                    <RankBadge rank={bot.rank} />
                  </td>
                  <td className="px-6 py-3.5">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-slate-700/40 text-base">
                        {bot.avatar}
                      </div>
                      <span className="text-sm font-medium text-slate-200">{bot.name}</span>
                    </div>
                  </td>
                  <td className="px-6 py-3.5 text-right">
                    <span className="text-sm font-semibold text-white tabular-nums">
                      {bot.conversations.toLocaleString()}
                    </span>
                  </td>
                  <td className="px-6 py-3.5 text-right">
                    <span
                      className={cn(
                        'text-sm font-semibold tabular-nums',
                        bot.bookingRate >= 35
                          ? 'text-emerald-400'
                          : bot.bookingRate >= 25
                          ? 'text-cyan-400'
                          : 'text-slate-300'
                      )}
                    >
                      {bot.bookingRate}%
                    </span>
                  </td>
                  <td className="px-6 py-3.5">
                    <CsatBar score={bot.csatScore} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
