'use client';

import { useEffect, useState } from 'react';
import { Trophy, Medal, Crown, Calendar, Clock, TrendingUp, Globe } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/ui/EmptyState';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';

type Period = 'daily' | 'weekly' | 'monthly' | 'all-time';

interface PeriodRankingEntry {
  rank: number;
  position: number;
  points: number;
  exercisesCompleted: number;
  streak: number;
  perfectExercises: number;
  achievementsUnlocked: number;
}

interface PeriodRankingResponse {
  rankings: PeriodRankingEntry[];
  period: Period;
  pagination: {
    limit: number;
    offset: number;
    total: number;
    hasMore: boolean;
  };
}

interface PeriodConfig {
  label: string;
  icon: LucideIcon;
  description: string;
}

const periodConfig: Record<Period, PeriodConfig> = {
  daily: {
    label: 'Hoy',
    icon: Clock,
    description: 'Puntos ganados en las últimas 24 horas',
  },
  weekly: {
    label: 'Esta semana',
    icon: Calendar,
    description: 'Puntos ganados en los últimos 7 días',
  },
  monthly: {
    label: 'Este mes',
    icon: TrendingUp,
    description: 'Puntos ganados en los últimos 30 días',
  },
  'all-time': {
    label: 'Todos los tiempos',
    icon: Globe,
    description: 'Puntos totales acumulados',
  },
};

export default function RankingPage() {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [selectedPeriod, setSelectedPeriod] = useState<Period>('all-time');
  const [rankingData, setRankingData] = useState<PeriodRankingEntry[]>([]);
  const [totalUsers, setTotalUsers] = useState(0);

  useEffect(() => {
    const fetchRanking = async () => {
      try {
        setIsLoading(true);
        const data = await api.get<PeriodRankingResponse>(
          apiEndpoints.ranking.period,
          { period: selectedPeriod, limit: 100 }
        );
        setRankingData(data.rankings);
        setTotalUsers(data.pagination.total);
      } catch (error) {
        toast({
          title: 'Error al cargar ranking',
          description: error instanceof Error ? error.message : 'No se pudo cargar el ranking',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };

    void fetchRanking();
  }, [toast, selectedPeriod]);

  const periods: Period[] = ['daily', 'weekly', 'monthly', 'all-time'];
  const topThree = rankingData.slice(0, 3);
  const restOfRanking = rankingData.slice(3);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Ranking</h1>
        <p className="text-muted-foreground">
          Compite con otros estudiantes
        </p>
      </div>

      {/* Period Tabs */}
      <div className="flex flex-wrap gap-2">
        {periods.map((period) => {
          const config = periodConfig[period];
          const Icon = config.icon;
          return (
            <Button
              key={period}
              variant={selectedPeriod === period ? 'default' : 'outline'}
              onClick={() => setSelectedPeriod(period)}
              className="gap-2"
            >
              <Icon className="h-4 w-4" />
              {config.label}
            </Button>
          );
        })}
      </div>

      {/* Period Description */}
      <p className="text-sm text-muted-foreground">
        {periodConfig[selectedPeriod].description}
      </p>

      {isLoading ? (
        <div className="flex h-64 items-center justify-center">
          <div className="flex flex-col items-center gap-4">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            <p className="text-sm text-muted-foreground">Cargando ranking...</p>
          </div>
        </div>
      ) : rankingData.length === 0 ? (
        <Card>
          <CardContent className="py-12">
            <EmptyState
              icon={<Trophy className="h-12 w-12" />}
              title="Sin datos para este período"
              description="No hay usuarios con puntos en este período. Sé el primero en completar ejercicios."
            />
          </CardContent>
        </Card>
      ) : (
        <>
          {/* Stats */}
          <Card>
            <CardContent className="py-4">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Total participantes:</span>
                <span className="font-medium">{totalUsers}</span>
              </div>
            </CardContent>
          </Card>

          {/* Top 3 */}
          {topThree.length > 0 && (
            <div className="grid gap-4 md:grid-cols-3">
              {topThree.map((rankUser, index) => {
                const bgList: string[] = ['bg-yellow-500/10', 'bg-gray-400/10', 'bg-orange-500/10'];
                const bgClass = bgList[index];
                return (
                  <Card key={index} className={cn(bgClass, 'relative overflow-hidden')}>
                    <div className="absolute top-0 right-0 p-2">
                      {index === 0 && <Crown className="h-6 w-6 text-yellow-500" />}
                      {index === 1 && <Medal className="h-6 w-6 text-gray-400" />}
                      {index === 2 && <Medal className="h-6 w-6 text-orange-500" />}
                    </div>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium">
                        #{rankUser.rank}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-1">
                        <p className="text-2xl font-bold">{rankUser.points}</p>
                        <p className="text-sm text-muted-foreground">puntos</p>
                      </div>
                      <div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
                        <span>{rankUser.exercisesCompleted} ejercicios</span>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {/* Rest of ranking */}
          {restOfRanking.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Ranking completo</CardTitle>
                <CardDescription>
                  Posiciones 4-{rankingData.length} de {totalUsers}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {restOfRanking.map((rankUser) => (
                    <div
                      key={rankUser.rank}
                      className="flex items-center justify-between p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors"
                    >
                      <div className="flex items-center gap-3">
                        <span className="text-sm font-medium text-muted-foreground w-8">
                          #{rankUser.rank}
                        </span>
                        <div>
                          <p className="font-medium">{rankUser.points} puntos</p>
                          <p className="text-xs text-muted-foreground">
                            {rankUser.exercisesCompleted} ejercicios completados
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {rankUser.perfectExercises > 0 && (
                          <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">
                            {rankUser.perfectExercises} perfectos
                          </span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}
    </div>
  );
}
