'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Users,
  BookOpen,
  FileText,
  Trophy,
  TrendingUp,
  Activity,
  Target,
  CheckCircle,
} from 'lucide-react';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';

interface Stats {
  totalUsers: number;
  totalModules: number;
  totalExercises: number;
  publishedExercises: number;
  aiGeneratedExercises: number;
}

interface TopUser {
  userId: string;
  username: string;
  points: number;
  exercisesCompleted: number;
  currentStreak: number;
}

export default function AdminStatsPage() {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<Stats | null>(null);
  const [topUsers, setTopUsers] = useState<TopUser[]>([]);

  useEffect(() => {
    void fetchStats();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchStats = async () => {
    try {
      setIsLoading(true);

      const modulesData = await api.get<{ data: unknown[] }>(apiEndpoints.modules.list);
      const modules = Array.isArray(modulesData) ? modulesData : ((modulesData as Record<string, unknown>)['data'] as unknown[]) || [];

      const exercisesData = await api.get<{ data: unknown[] }>(apiEndpoints.exercises.list);
      const exercises = Array.isArray(exercisesData) ? exercisesData : ((exercisesData as Record<string, unknown>)['data'] as unknown[]) || [];

      let rankingData: Record<string, unknown>[] = [];
      try {
        const rankingResponse = await api.get<Record<string, unknown>[]>(apiEndpoints.ranking.global);
        rankingData = rankingResponse || [];
      } catch {
        // Ranking might be empty
      }

      const totalExercises = exercises.length;
      const publishedExercises = exercises.filter(e => (e as Record<string, unknown>)['isPublished']).length;
      const aiGenerated = exercises.filter(e => (e as Record<string, unknown>)['isAIGenerated']).length;

      setStats({
        totalUsers: rankingData.length || 0,
        totalModules: modules.length,
        totalExercises,
        publishedExercises,
        aiGeneratedExercises: aiGenerated,
      });

      setTopUsers(rankingData.slice(0, 10).map((r, i) => ({
        userId: String(r['userId'] ?? r['id'] ?? `user-${i}`),
        username: String(r['username'] ?? `Usuario ${i + 1}`),
        points: Number(r['points'] ?? 0),
        exercisesCompleted: Number(r['exercisesCompleted'] ?? 0),
        currentStreak: Number(r['streak'] ?? r['currentStreak'] ?? 0),
      })));

    } catch (error) {
      toast({
        title: 'Error al cargar estadísticas',
        description: error instanceof Error ? error.message : 'No se pudo cargar las estadísticas',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-48" />
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map(i => <Skeleton key={i} className="h-32" />)}
        </div>
        <div className="grid gap-6 lg:grid-cols-2">
          <Skeleton className="h-96" />
          <Skeleton className="h-96" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Estadísticas</h1>
        <p className="text-muted-foreground">Métricas detalladas de la plataforma</p>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Usuarios registrados</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.totalUsers ?? 0}</div>
            <p className="text-xs text-muted-foreground">Usuarios activos en el ranking</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Módulos</CardTitle>
            <BookOpen className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.totalModules ?? 0}</div>
            <p className="text-xs text-muted-foreground">Módulos disponibles</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Ejercicios</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats?.publishedExercises ?? 0}/{stats?.totalExercises ?? 0}</div>
            <p className="text-xs text-muted-foreground">Publicados vs totales</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Generados con IA</CardTitle>
            <Activity className="h-4 w-4 text-amber-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-amber-500">{stats?.aiGeneratedExercises ?? 0}</div>
            <p className="text-xs text-muted-foreground">Ejercicios creados por IA</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Trophy className="h-5 w-5 text-yellow-500" />
              Top 10 Usuarios
            </CardTitle>
            <CardDescription>Usuarios con más puntos acumulados</CardDescription>
          </CardHeader>
          <CardContent>
            {topUsers.length > 0 ? (
              <div className="space-y-4">
                {topUsers.map((user, index) => (
                  <div key={user.userId} className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`flex h-8 w-8 items-center justify-center rounded-full ${
                        index === 0 ? 'bg-yellow-500/20 text-yellow-600' :
                        index === 1 ? 'bg-gray-500/20 text-gray-600' :
                        index === 2 ? 'bg-amber-500/20 text-amber-600' :
                        'bg-muted text-muted-foreground'
                      }`}>
                        {index + 1}
                      </div>
                      <div>
                        <p className="font-medium">{user.username}</p>
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <span>{user.exercisesCompleted} ejercicios</span>
                          {user.currentStreak > 0 && (
                            <Badge variant="outline" className="text-xs">
                              🔥 {user.currentStreak}
                            </Badge>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-semibold">{user.points} pts</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="py-8 text-center text-muted-foreground">
                <Trophy className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No hay datos de ranking disponibles</p>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5 text-green-500" />
              Métricas de Performance
            </CardTitle>
            <CardDescription>Indicadores de rendimiento de la plataforma</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Tasa de publicación de ejercicios</span>
                <span className="text-sm text-muted-foreground">
                  {Math.round((stats?.publishedExercises ?? 0) / (stats?.totalExercises ?? 1) * 100)}%
                </span>
              </div>
              <Progress value={(stats?.publishedExercises ?? 0) / (stats?.totalExercises ?? 1) * 100} />
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Ejercicios generados con IA</span>
                <span className="text-sm text-muted-foreground">
                  {Math.round((stats?.aiGeneratedExercises ?? 0) / (stats?.totalExercises ?? 1) * 100)}%
                </span>
              </div>
              <Progress
                value={(stats?.aiGeneratedExercises ?? 0) / (stats?.totalExercises ?? 1) * 100}
                className="[&>div]:bg-amber-500"
              />
            </div>

            <div className="grid grid-cols-2 gap-4 pt-4">
              <div className="flex items-center gap-3 rounded-lg bg-muted/50 p-3">
                <Target className="h-5 w-5 text-blue-500" />
                <div>
                  <p className="text-sm font-medium">Módulos activos</p>
                  <p className="text-xs text-muted-foreground">{stats?.totalModules ?? 0}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 rounded-lg bg-muted/50 p-3">
                <CheckCircle className="h-5 w-5 text-green-500" />
                <div>
                  <p className="text-sm font-medium">Ejercicios publicados</p>
                  <p className="text-xs text-muted-foreground">{stats?.publishedExercises ?? 0}</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
