import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Trophy, ChevronLeft, ChevronRight } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Avatar } from '@/components/ui/Avatar';
import { Badge } from '@/components/ui/Badge';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { Podium } from '@/components/leaderboard/Podium';
import { leaderboardAPI } from '@/api/client';
import { useAuthStore } from '@/stores/authStore';
import { cn } from '@/lib/cn';
import { formatNumber } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function Leaderboard() {
  const user = useAuthStore((s) => s.user);
  const [players, setPlayers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 50;
  const totalPages = Math.max(1, Math.ceil(total / limit));

  useEffect(() => {
    setLoading(true);
    leaderboardAPI.get({ page, limit })
      .then(({ data }) => {
        setPlayers(data.players || []);
        setTotal(data.total || 0);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page]);

  const top3 = players.slice(0, 3);
  const rest = players.slice(3);

  return (
    <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="text-center mb-10">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ type: 'spring', stiffness: 200, damping: 20 }}
          className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#ff6b2c]/10 border border-[#ff6b2c]/20 mb-4"
        >
          <Trophy className="w-3.5 h-3.5 text-[#ff6b2c]" />
          <span className="text-xs font-medium text-[#ff8a50] uppercase tracking-wider">Rankings</span>
        </motion.div>
        <motion.h1
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="text-3xl sm:text-4xl font-extrabold text-[#f0f0f5] tracking-tight"
        >
          Leaderboard
        </motion.h1>
        <motion.p
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15 }}
          className="text-sm text-[#a0a0b8] mt-2"
        >
          {total} ranked player{total !== 1 ? 's' : ''}
        </motion.p>
      </div>

      {loading ? (
        <div className="space-y-3">{[...Array(10)].map((_, i) => <SkeletonRow key={i} />)}</div>
      ) : (
        <>
          {page === 1 && top3.length >= 3 && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
              className="mb-10"
            >
              <Podium
                players={top3.map((p) => ({
                  username: p.username,
                  mmr: p.mmr,
                  wins: p.wins,
                  losses: p.losses,
                  avatar_url: p.steam_avatar_url || p.avatar_url,
                  placement_done: true,
                }))}
              />
            </motion.div>
          )}

          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
          >
            <Card padding={false}>
              <div className="grid grid-cols-[48px_1fr_100px_80px_80px] sm:grid-cols-[48px_1fr_120px_100px_100px] gap-2 px-5 py-3 text-[10px] text-[#5a5a72] uppercase tracking-widest font-medium border-b border-[#1e1e30]">
                <span>#</span>
                <span>Player</span>
                <span className="text-right">MMR</span>
                <span className="text-right">Win Rate</span>
                <span className="text-right">Matches</span>
              </div>

              <motion.div variants={staggerContainer} initial="initial" animate="animate">
                {rest.map((player, i) => {
                  const rank = player.rank || ((page - 1) * limit + i + 4);
                  const isUser = player.id === user?.id || player.username === user?.username;
                  const totalMatches = player.matches_played || (player.wins + player.losses);
                  const winRate = player.win_rate != null
                    ? Math.round(player.win_rate)
                    : totalMatches > 0
                      ? Math.round((player.wins / totalMatches) * 100)
                      : 0;

                  return (
                    <motion.div key={player.id || player.username} variants={staggerItem}>
                      <Link
                        to={`/player/${player.username}`}
                        className={cn(
                          'grid grid-cols-[48px_1fr_100px_80px_80px] sm:grid-cols-[48px_1fr_120px_100px_100px] gap-2 px-5 py-3 items-center border-b border-[#0f0f18] last:border-0 transition-all duration-200 hover:bg-[#1a1a28]/30 group',
                          isUser && 'bg-[#ff6b2c]/[0.04] hover:bg-[#ff6b2c]/[0.06]'
                        )}
                      >
                        <span className={cn(
                          'text-sm font-mono',
                          rank <= 10 ? 'text-[#ff8a50] font-bold' : 'text-[#5a5a72]'
                        )}>
                          {rank}
                        </span>

                        <div className="flex items-center gap-2.5 min-w-0">
                          <Avatar src={player.steam_avatar_url || player.avatar_url} username={player.username} size="sm" />
                          <span className={cn(
                            'text-sm font-medium truncate group-hover:text-[#f0f0f5] transition-colors',
                            isUser ? 'text-[#ff8a50]' : 'text-[#f0f0f5]'
                          )}>
                            {player.username}
                            {isUser && (
                              <span className="text-xs text-[#ff6b2c]/60 ml-1">(You)</span>
                            )}
                          </span>
                          {player.tier === 'premium' && <Badge variant="premium">PRO</Badge>}
                          {player.tier === 'vip' && <Badge variant="vip">VIP</Badge>}
                        </div>

                        <span className="text-sm font-mono font-bold text-[#ff8a50] text-right">
                          {formatNumber(player.mmr)}
                        </span>

                        <span className={cn(
                          'text-sm font-mono text-right',
                          winRate >= 55 ? 'text-emerald-400' : winRate >= 45 ? 'text-[#a0a0b8]' : 'text-red-400'
                        )}>
                          {winRate}%
                        </span>

                        <span className="text-sm font-mono text-[#a0a0b8] text-right">
                          {totalMatches}
                        </span>
                      </Link>
                    </motion.div>
                  );
                })}
              </motion.div>
            </Card>
          </motion.div>

          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 mt-8">
              <button
                onClick={() => setPage(Math.max(1, page - 1))}
                disabled={page === 1}
                className={cn(
                  'w-9 h-9 rounded-lg flex items-center justify-center transition-colors',
                  page === 1 ? 'text-[#5a5a72]/30 cursor-not-allowed' : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
                )}
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                let p: number;
                if (totalPages <= 7) {
                  p = i + 1;
                } else if (page <= 4) {
                  p = i + 1;
                } else if (page >= totalPages - 3) {
                  p = totalPages - 6 + i;
                } else {
                  p = page - 3 + i;
                }
                return (
                  <button
                    key={p}
                    onClick={() => setPage(p)}
                    className={cn(
                      'w-9 h-9 rounded-lg text-sm font-medium transition-all relative',
                      p === page
                        ? 'text-white'
                        : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
                    )}
                  >
                    {p === page && (
                      <motion.div
                        layoutId="lb-page-active"
                        className="absolute inset-0 bg-[#ff6b2c] rounded-lg"
                        transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                      />
                    )}
                    <span className="relative z-10">{p}</span>
                  </button>
                );
              })}
              <button
                onClick={() => setPage(Math.min(totalPages, page + 1))}
                disabled={page === totalPages}
                className={cn(
                  'w-9 h-9 rounded-lg flex items-center justify-center transition-colors',
                  page === totalPages ? 'text-[#5a5a72]/30 cursor-not-allowed' : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
                )}
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          )}
        </>
      )}
    </PageTransition>
  );
}
