'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Users,
  BookOpen,
  FileText,
  Trophy,
  TrendingUp,
  Activity,
  Sparkles,
  Clock,
} from 'lucide-react';
import Link from 'next/link';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';

interface AdminStats {
  totalUsers: number;
  totalModules: number;
  totalExercises: number;
  publishedExercises: number;
  totalAttempts: number;
  correctRate: number;
  aiGeneratedExercises: number;
  recentActivity: {
    date: string;
    attempts: number;
    newUsers: number;
  }[];
}

interface TopUser {
  id: string;
  username: string;
  points: number;
  exercisesCompleted: number;
  position: number;
}

interface Module {
  id: string;
  name: string;
  isPublished: boolean;
}

interface Exercise {
  id: string;
  isPublished: boolean;
  isAIGenerated: boolean;
}

interface RankingEntry {
  userId?: string;
  id?: string;
  username?: string;
  points?: number;
  exercisesCompleted?: number;
}

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

  useEffect(() => {
    const fetchAdminData = async () => {
      try {
        setIsLoading(true);

        // Fetch modules for basic stats
        const modules = await api.get<Module[]>(apiEndpoints.modules.list);
        const exercises = await api.get<Exercise[]>(apiEndpoints.exercises.list);

        // Fetch ranking for top users
        let rankingData: RankingEntry[] = [];
        try {
          rankingData = await api.get<RankingEntry[]>(apiEndpoints.ranking.global);
        } catch {
          // Ranking might be empty
        }

        setStats({
          totalUsers: rankingData.length ?? 0,
          totalModules: modules.length,
          totalExercises: exercises.length,
          publishedExercises: exercises.filter(e => e.isPublished).length,
          totalAttempts: 0,
          correctRate: 0,
          aiGeneratedExercises: exercises.filter(e => e.isAIGenerated).length,
          recentActivity: [],
        });

        setTopUsers(rankingData.slice(0, 5).map((r, i) => ({
          id: r.userId ?? r.id ?? '',
          username: r.username ?? `Usuario ${i + 1}`,
          points: r.points ?? 0,
          exercisesCompleted: r.exercisesCompleted ?? 0,
          position: i + 1,
        })));

      } catch (error) {
        toast({
          title: 'Error al cargar datos',
          description: error instanceof Error ? error.message : 'No se pudo cargar la información',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };

    void fetchAdminData();
  }, [toast]);

  const statCards = [
    {
      title: 'Usuarios registrados',
      value: stats?.totalUsers ?? 0,
      icon: Users,
      color: 'text-blue-500',
      bgColor: 'bg-blue-500/10',
    },
    {
      title: 'Módulos',
      value: stats?.totalModules ?? 0,
      icon: BookOpen,
      color: 'text-green-500',
      bgColor: 'bg-green-500/10',
    },
    {
      title: 'Ejercicios publicados',
      value: `${stats?.publishedExercises ?? 0}/${stats?.totalExercises ?? 0}`,
      icon: FileText,
      color: 'text-purple-500',
      bgColor: 'bg-purple-500/10',
    },
    {
      title: 'Ejercicios IA',
      value: stats?.aiGeneratedExercises ?? 0,
      icon: Sparkles,
      color: 'text-amber-500',
      bgColor: 'bg-amber-500/10',
    },
  ];

  if (isLoading) {
    return (
      <div className="flex h-full 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 dashboard...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Panel de Administración</h1>
        <p className="text-muted-foreground">
          Gestiona la plataforma de Math2
        </p>
      </div>

      {/* Stats Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {statCards.map((stat) => (
          <Card key={stat.title}>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">
                {stat.title}
              </CardTitle>
              <div className={`rounded-lg p-2 ${stat.bgColor}`}>
                <stat.icon className={`h-4 w-4 ${stat.color}`} />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stat.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Quick Actions */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Link href="/admin/modules">
          <Card className="cursor-pointer hover:bg-accent transition-colors">
            <CardContent className="flex items-center gap-4 pt-6">
              <div className="rounded-lg bg-green-500/10 p-3">
                <BookOpen className="h-6 w-6 text-green-500" />
              </div>
              <div>
                <p className="font-semibold">Gestionar Módulos</p>
                <p className="text-sm text-muted-foreground">Crear, editar y publicar</p>
              </div>
            </CardContent>
          </Card>
        </Link>

        <Link href="/admin/exercises">
          <Card className="cursor-pointer hover:bg-accent transition-colors">
            <CardContent className="flex items-center gap-4 pt-6">
              <div className="rounded-lg bg-purple-500/10 p-3">
                <FileText className="h-6 w-6 text-purple-500" />
              </div>
              <div>
                <p className="font-semibold">Gestionar Ejercicios</p>
                <p className="text-sm text-muted-foreground">Editar y publicar</p>
              </div>
            </CardContent>
          </Card>
        </Link>

        <Link href="/admin/generate">
          <Card className="cursor-pointer hover:bg-accent transition-colors">
            <CardContent className="flex items-center gap-4 pt-6">
              <div className="rounded-lg bg-amber-500/10 p-3">
                <Sparkles className="h-6 w-6 text-amber-500" />
              </div>
              <div>
                <p className="font-semibold">Generar con IA</p>
                <p className="text-sm text-muted-foreground">Crear ejercicios automáticamente</p>
              </div>
            </CardContent>
          </Card>
        </Link>

        <Link href="/admin/stats">
          <Card className="cursor-pointer hover:bg-accent transition-colors">
            <CardContent className="flex items-center gap-4 pt-6">
              <div className="rounded-lg bg-blue-500/10 p-3">
                <TrendingUp className="h-6 w-6 text-blue-500" />
              </div>
              <div>
                <p className="font-semibold">Ver Estadísticas</p>
                <p className="text-sm text-muted-foreground">Métricas detalladas</p>
              </div>
            </CardContent>
          </Card>
        </Link>
      </div>

      {/* Tables */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Top Users */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Trophy className="h-5 w-5 text-yellow-500" />
              Top 5 Usuarios
            </CardTitle>
          </CardHeader>
          <CardContent>
            {topUsers.length > 0 ? (
              <div className="space-y-4">
                {topUsers.map((user) => (
                  <div key={user.id} 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 ${
                        user.position === 1 ? 'bg-yellow-500/20 text-yellow-600' :
                        user.position === 2 ? 'bg-gray-500/20 text-gray-600' :
                        user.position === 3 ? 'bg-amber-500/20 text-amber-600' :
                        'bg-muted text-muted-foreground'
                      }`}>
                        {user.position}
                      </div>
                      <div>
                        <p className="font-medium">{user.username}</p>
                        <p className="text-sm text-muted-foreground">
                          {user.exercisesCompleted} ejercicios
                        </p>
                      </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">
                No hay datos de ranking aún
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5 text-green-500" />
              Actividad Reciente
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between rounded-lg bg-muted/50 p-3">
                <div className="flex items-center gap-3">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">Hoy</span>
                </div>
                <div className="text-sm text-muted-foreground">
                  Sin actividad registrada
                </div>
              </div>
              <div className="flex items-center justify-between rounded-lg bg-muted/50 p-3">
                <div className="flex items-center gap-3">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">Ayer</span>
                </div>
                <div className="text-sm text-muted-foreground">
                  Sin actividad registrada
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}