'use client';

import { useEffect, useState, useRef, useCallback } from 'react';
import { BookOpen, Trophy, Target, TrendingUp, Star, Flame } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { ModuleCard } from '@/components/modules/ModuleCard';
import { useModuleStore } from '@/store/useModuleStore';
import { useAuthStore } from '@/store/useAuthStore';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import type { Module, Progress } from '@/types';
import Link from 'next/link';

interface ProgressResponse {
  totalPoints: number;
  totalExercisesCompleted: number;
  totalModulesCompleted: number;
  currentStreak: number;
  averageScore: number;
  perfectExercises: number;
  totalAttempts: number;
  modules: Progress[];
}

interface RankingPositionResponse {
  global: { position: number };
}

export default function DashboardPage() {
  const { toast } = useToast();
  const { user } = useAuthStore();
  const setModules = useModuleStore((state) => state.setModules);
  const setProgress = useModuleStore((state) => state.setProgress);
  const modules = useModuleStore((state) => state.modules);
  const progress = useModuleStore((state) => state.progress);
  const [isLoading, setIsLoading] = useState(true);
  const hasFetchedRef = useRef(false);

  // Stats from the API
  const [stats, setStats] = useState({
    totalPoints: 0,
    exercisesCompleted: 0,
    modulesCompleted: 0,
    currentStreak: 0,
    rank: 0,
    weeklyProgress: 0,
  });

  const fetchDashboardData = useCallback(async () => {
    if (hasFetchedRef.current) return;
    hasFetchedRef.current = true;

    try {
      setIsLoading(true);

      const modulesData = await api.get<Module[]>(apiEndpoints.modules.list);
      setModules(modulesData);

      try {
        const progressResponse = await api.get<ProgressResponse>(apiEndpoints.progress.overview);
        setProgress(progressResponse.modules ?? []);
        // Use root-level stats from the API response
        setStats((prev) => ({
          ...prev,
          totalPoints: progressResponse.totalPoints ?? 0,
          exercisesCompleted: progressResponse.totalExercisesCompleted ?? 0,
          modulesCompleted: progressResponse.totalModulesCompleted ?? 0,
          currentStreak: progressResponse.currentStreak ?? 0,
        }));
      } catch {
        // No progress data yet - silently ignore
      }

      try {
        const rankingResponse = await api.get<RankingPositionResponse>(apiEndpoints.ranking.myPosition);
        setStats((prev) => ({ ...prev, rank: rankingResponse.global?.position ?? 0 }));
      } catch {
        // No ranking data yet - silently ignore
      }
    } 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);
    }
  }, [setModules, setProgress, toast]);

  useEffect(() => {
    void fetchDashboardData();
  }, [fetchDashboardData]);

  const statCards = [
    {
      title: 'Puntos totales',
      value: stats.totalPoints,
      icon: Trophy,
      color: 'text-yellow-500',
      bgColor: 'bg-yellow-500/10',
    },
    {
      title: 'Ejercicios completados',
      value: stats.exercisesCompleted,
      icon: Target,
      color: 'text-blue-500',
      bgColor: 'bg-blue-500/10',
    },
    {
      title: 'Módulos completados',
      value: `${stats.modulesCompleted}/${modules.length}`,
      icon: BookOpen,
      color: 'text-green-500',
      bgColor: 'bg-green-500/10',
    },
    {
      title: 'Racha actual',
      value: `${stats.currentStreak} días`,
      icon: Flame,
      color: 'text-orange-500',
      bgColor: 'bg-orange-500/10',
    },
  ];

  const getModuleProgress = (moduleId: string) => {
    return progress.find((p) => p.moduleId === moduleId);
  };

  const recommendedModules = modules
    .filter((m) => {
      const moduleProgress = getModuleProgress(m.id);
      return !moduleProgress?.isCompleted;
    })
    .slice(0, 3);

  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">
      {/* Welcome Section */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">
          ¡Hola, {user?.username ?? 'Usuario'}! 👋
        </h1>
        <p className="text-muted-foreground">
          Continúa tu aprendizaje de Álgebra Lineal
        </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>

      {/* Continue Learning Section */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Recommended Modules */}
        <div className="lg:col-span-2 space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold">Continúa aprendiendo</h2>
              <p className="text-sm text-muted-foreground">
                Retoma donde lo dejaste
              </p>
            </div>
            <Link href="/modules">
              <Button variant="outline" size="sm">
                Ver todos
              </Button>
            </Link>
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            {recommendedModules.length > 0 ? (
              recommendedModules.map((module) => {
                const moduleProgress = getModuleProgress(module.id);
                return (
                  <ModuleCard
                    key={module.id}
                    module={module}
                    {...(moduleProgress !== undefined && { progress: moduleProgress })}
                  />
                );
              })
            ) : modules.length === 0 ? (
              <Card className="col-span-2">
                <CardContent className="flex flex-col items-center justify-center py-12">
                  <BookOpen className="mb-4 h-12 w-12 text-muted-foreground" />
                  <h3 className="text-lg font-semibold">
                    No hay módulos disponibles
                  </h3>
                  <p className="mb-4 text-center text-muted-foreground">
                    El contenido estará disponible pronto.
                  </p>
                </CardContent>
              </Card>
            ) : (
              <Card className="col-span-2">
                <CardContent className="flex flex-col items-center justify-center py-12">
                  <Trophy className="mb-4 h-12 w-12 text-muted-foreground" />
                  <h3 className="text-lg font-semibold">
                    ¡Has completado todos los módulos!
                  </h3>
                  <p className="mb-4 text-center text-muted-foreground">
                    Eres un maestro del Álgebra Lineal
                  </p>
                  <Button asChild>
                    <Link href="/modules">
                      Practicar ejercicios
                    </Link>
                  </Button>
                </CardContent>
              </Card>
            )}
          </div>
        </div>

        {/* Quick Actions */}
        <div className="space-y-4">
          <h2 className="text-xl font-semibold">Accesos rápidos</h2>
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Progreso semanal</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-2xl font-bold">{stats.weeklyProgress}%</p>
                  <p className="text-xs text-muted-foreground">
                    vs semana pasada
                  </p>
                </div>
                <TrendingUp className="h-8 w-8 text-green-500" />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Próximo objetivo</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <Star className="h-5 w-5 text-primary" />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium">Completa un módulo</p>
                  <p className="text-xs text-muted-foreground">
                    {stats.modulesCompleted} de {modules.length}
                  </p>
                </div>
              </div>
              <Link href="/modules">
                <Button variant="outline" className="w-full" size="sm">
                  Continuar
                </Button>
              </Link>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Ranking</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-2xl font-bold">#{stats.rank || '-'}</p>
                  <p className="text-xs text-muted-foreground">
                    Tu posición global
                  </p>
                </div>
                <Trophy className="h-8 w-8 text-yellow-500" />
              </div>
              <Link href="/ranking">
                <Button variant="outline" className="mt-3 w-full" size="sm">
                  Ver ranking completo
                </Button>
              </Link>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
