'use client';

import { useEffect, useState } from 'react';
import { motion } from 'motion/react';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
import { Trophy, Clock } from 'lucide-react';
import { PlayerTooltip } from '@/components/player-tooltip';

interface LeaderboardPlayer {
  name: string;
  playtime: number;
  playtimeFormatted: string;
  sessions: number;
}

interface LeaderboardData {
  players: LeaderboardPlayer[];
  total: number;
  error?: string;
}

const getRankBadge = (rank: number) => {
  if (rank === 1) return '🥇';
  if (rank === 2) return '🥈';
  if (rank === 3) return '🥉';
  return `#${rank}`;
};


export function Leaderboard({ className }: { className?: string }) {
  const [data, setData] = useState<LeaderboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchLeaderboard = async () => {
      try {
        const response = await fetch('/api/leaderboard');
        if (!response.ok) {
          throw new Error('Failed to fetch leaderboard');
        }
        const leaderboardData = await response.json() as LeaderboardData;
        setData(leaderboardData);
        setError(null);
      } catch (err) {
        setError('Failed to load leaderboard');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchLeaderboard();
    // Refresh every minute
    const interval = setInterval(fetchLeaderboard, 60000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <div className={cn("w-full flex flex-col", className)} style={{ height: '100%', minHeight: 0 }}>
        <div className="flex items-center gap-2 mb-4 flex-shrink-0">
          <Trophy className="h-4 w-4 text-primary" />
          <h2 className="text-base font-semibold">Top Players</h2>
        </div>
        <div className="flex-1 overflow-y-auto hide-scrollbar" style={{ minHeight: 0 }}>
          <div className="space-y-2">
            {[1, 2, 3, 4, 5, 6].map((i) => (
              <div key={i} className="flex items-center gap-2 p-2 rounded-lg border border-border/50">
                <Skeleton className="h-5 w-5 rounded-full" />
                <Skeleton className="h-3 flex-1" />
                <Skeleton className="h-3 w-12" />
              </div>
            ))}
            {/* Spacer to prevent last item from being cut off */}
            <div style={{ height: '2rem', minHeight: '2rem', flexShrink: 0 }} aria-hidden="true" />
          </div>
        </div>
      </div>
    );
  }

  if (error || !data || data.players.length === 0) {
    return (
      <div className={cn("w-full flex flex-col", className)} style={{ height: '100%', minHeight: 0 }}>
        <div className="flex items-center gap-2 mb-4 flex-shrink-0">
          <Trophy className="h-4 w-4 text-primary" />
          <h2 className="text-base font-semibold">Top Players</h2>
        </div>
        <div className="flex-1 flex items-center justify-center">
          <p className="text-xs text-muted-foreground text-center">
            {error || 'No leaderboard data available'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <motion.div
      className={cn("w-full flex flex-col relative", className)}
      initial={{ opacity: 0, x: -20 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ duration: 0.5 }}
      style={{ height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column' }}
    >
      <div className="flex items-center gap-2 mb-4 flex-shrink-0">
        <Trophy className="h-4 w-4 text-primary" />
        <h2 className="text-base font-semibold">Top Players</h2>
      </div>
      <div className="flex-1 overflow-y-auto hide-scrollbar" style={{ minHeight: 0 }}>
        <div className="space-y-1.5" style={{ paddingBottom: '2.5rem' }}>
          {data.players.slice(0, 10).map((player, index) => {
          const rank = index + 1;
          const isTopThree = rank <= 3;

          return (
            <motion.div
              key={player.name}
              className={cn(
                "flex items-center gap-2 p-2 rounded-lg border transition-all duration-200 ease-out text-sm",
                isTopThree
                  ? "bg-primary/5 border-primary/20 shadow-sm hover:scale-[1.02] hover:border-primary/30"
                  : "bg-background/50 border-border/50 hover:scale-[1.02] hover:border-primary/30"
              )}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.2, delay: index * 0.03, ease: [0.4, 0, 0.2, 1] }}
            >
              <div className={cn(
                "flex items-center justify-center w-6 h-6 rounded-full font-bold text-xs flex-shrink-0 border transition-all duration-200",
                rank === 1 && "bg-primary/10 border-primary/30 text-primary",
                rank === 2 && "bg-primary/10 border-primary/30 text-primary",
                rank === 3 && "bg-primary/10 border-primary/30 text-primary",
                rank > 3 && "bg-muted text-muted-foreground border-border/50"
              )}>
                {rank <= 3 ? getRankBadge(rank) : rank}
              </div>
              <div className="flex-1 min-w-0">
                <PlayerTooltip playerName={player.name}>
                  <p className={cn(
                    "font-semibold truncate text-xs cursor-pointer",
                    isTopThree && "text-primary"
                  )}>
                    {player.name}
                  </p>
                </PlayerTooltip>
                <div className="flex items-center gap-2 mt-0.5 text-[10px] text-muted-foreground">
                  <span className="flex items-center gap-0.5">
                    <Clock className="h-2.5 w-2.5" />
                    {player.playtimeFormatted}
                  </span>
                </div>
              </div>
            </motion.div>
          );
          })}
        </div>
      </div>
    </motion.div>
  );
}

