'use client';

import { useEffect, useState } from 'react';
import { TrendingUp, Target, BookOpen, Trophy } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { EmptyState } from '@/components/ui/EmptyState';
import { Progress } from '@/components/ui/progress';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { useModuleStore } from '@/store/useModuleStore';
import type { Module, Progress as ProgressType } from '@/types';
import Link from 'next/link';
import { Button } from '@/components/ui/button';

interface UserStats {
  totalPoints: number;
  exercisesCompleted: number;
  modulesCompleted: number;
  currentStreak: number;
  weeklyProgress: number;
}

export default function ProgressPage() {
  const { toast } = useToast();
  const { modules, progress, setModules, setProgress } = useModuleStore();
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<UserStats>({
    totalPoints: 0,
    exercisesCompleted: 0,
    modulesCompleted: 0,
    currentStreak: 0,
    weeklyProgress: 0,
  });

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

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

        try {
          const progressData = await api.get<ProgressType[]>(apiEndpoints.progress.overview);
          setProgress(progressData);

          const totalPoints = progressData.reduce((sum, p) => sum + p.points, 0);
          const exercisesCompleted = progressData.reduce((sum, p) => sum + p.exercisesCompleted, 0);
          const modulesCompleted = progressData.filter((p) => p.isCompleted).length;

          setStats({
            totalPoints,
            exercisesCompleted,
            modulesCompleted,
            currentStreak: 0,
            weeklyProgress: 0,
          });
        } catch {
          // No progress data yet
        }
      } catch (error) {
        toast({
          title: 'Error al cargar progreso',
          description: error instanceof Error ? error.message : 'No se pudo cargar el progreso',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };

    void fetchProgressData();
  }, [setModules, setProgress, toast]);

  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 progreso...</p>
        </div>
      </div>
    );
  }

  const hasProgress = stats.exercisesCompleted > 0 || stats.modulesCompleted > 0;

  if (!hasProgress) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Mi Progreso</h1>
          <p className="text-muted-foreground">
            Visualiza tu avance en el aprendizaje
          </p>
        </div>
        <Card>
          <CardContent>
            <EmptyState
              icon={<TrendingUp className="h-12 w-12" />}
              title="Sin progreso aún"
              description="Completa tu primer ejercicio para comenzar a ver tu progreso."
              action={{
                label: 'Ir a módulos',
                onClick: () => window.location.href = '/dashboard/modules',
              }}
            />
          </CardContent>
        </Card>
      </div>
    );
  }

  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: TrendingUp,
      color: 'text-orange-500',
      bgColor: 'bg-orange-500/10',
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Mi Progreso</h1>
        <p className="text-muted-foreground">
          Visualiza tu avance en el aprendizaje
        </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>

      {/* Module Progress */}
      <Card>
        <CardHeader>
          <CardTitle>Progreso por módulo</CardTitle>
          <CardDescription>Tu avance en cada módulo</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {modules.map((module) => {
              const moduleProgress = progress.find((p) => p.moduleId === module.id);
              const percentage = moduleProgress?.percentage ?? 0;
              const isCompleted = moduleProgress?.isCompleted ?? false;

              return (
                <div key={module.id} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Link
                      href={`/dashboard/modules/${module.id}`}
                      className="font-medium hover:underline"
                    >
                      {module.name}
                    </Link>
                    <span className="text-sm text-muted-foreground">
                      {percentage}%
                    </span>
                  </div>
                  <Progress value={percentage} className="h-2" />
                  {isCompleted && (
                    <span className="text-xs text-green-500">Completado</span>
                  )}
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Weekly Progress */}
      <Card>
        <CardHeader>
          <CardTitle>Progreso semanal</CardTitle>
          <CardDescription>Tu actividad esta semana</CardDescription>
        </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>

      {/* Quick Actions */}
      <Card>
        <CardHeader>
          <CardTitle>Acciones</CardTitle>
        </CardHeader>
        <CardContent className="flex gap-4">
          <Button asChild>
            <Link href="/dashboard/modules">Continuar aprendiendo</Link>
          </Button>
          <Button variant="outline" asChild>
            <Link href="/dashboard/ranking">Ver ranking</Link>
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}