'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import {
  ArrowLeft,
  Users,
  UserCheck,
  Calendar,
  Trophy,
  Target,
  DollarSign,
  TrendingUp,
  Activity,
  Award,
} from 'lucide-react';
import { toast } from 'sonner';

interface Estadisticas {
  ano: number;
  alumnos: {
    total: number;
    porCategoria: { categoria: string; cantidad: number }[];
  };
  profesores: { total: number };
  eventos: {
    total: number;
    porTipo: { ENTRENAMIENTO: number; AMISTOSO: number; CAMPEONATO: number };
    porMes: Record<number, number>;
  };
  asistencia: {
    totalAsistencias: number;
    totalAusencias: number;
    porcentaje: number;
  };
  partidos: {
    total: number;
    victorias: number;
    empates: number;
    derrotas: number;
    golesAFavor: number;
    golesEnContra: number;
    tarjetasAmarillas: number;
    tarjetasRojas: number;
  };
  topGoleadores: { alumnoId: string; nombre: string; categoria: string; goles: number }[];
  evaluaciones: { fisicas: number; deportivas: number };
  campeonatos: { activos: number };
  finanzas: { totalRecaudado: number; cantidadPagos: number };
}

const meses = [
  'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun',
  'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic',
];

export default function EstadisticasPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<Estadisticas | null>(null);
  const [ano, setAno] = useState(new Date().getFullYear().toString());

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login');
    }
  }, [status, router]);

  useEffect(() => {
    fetchEstadisticas();
  }, [ano]);

  const fetchEstadisticas = async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/estadisticas?ano=${ano}`);
      const data = await res.json();
      if (res.ok) {
        setStats(data);
      } else {
        toast.error(data.error || 'Error al cargar estadísticas');
      }
    } catch {
      toast.error('Error de conexión');
    } finally {
      setLoading(false);
    }
  };

  if (status === 'loading' || loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
      </div>
    );
  }

  const currentYear = new Date().getFullYear();
  const years = Array.from({ length: 5 }, (_, i) => (currentYear - i).toString());

  const maxEventosMes = stats ? Math.max(...Object.values(stats.eventos.porMes)) : 1;

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => router.push('/dashboard')}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            Volver
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Estadísticas Globales</h1>
            <p className="text-gray-500">Resumen general de la escuela</p>
          </div>
        </div>
        <Select value={ano} onValueChange={setAno}>
          <SelectTrigger className="w-32">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {years.map((y) => (
              <SelectItem key={y} value={y}>
                {y}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {stats && (
        <>
          {/* Tarjetas principales */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card className="border-l-4 border-l-blue-500">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Total Alumnos</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Users className="h-8 w-8 text-blue-500" />
                  <span className="text-3xl font-bold">{stats.alumnos.total}</span>
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  {stats.alumnos.porCategoria.length} categorías activas
                </p>
              </CardContent>
            </Card>

            <Card className="border-l-4 border-l-green-500">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Asistencia Promedio</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <UserCheck className="h-8 w-8 text-green-500" />
                  <span className="text-3xl font-bold">{stats.asistencia.porcentaje}%</span>
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  {stats.asistencia.totalAsistencias} asistencias registradas
                </p>
              </CardContent>
            </Card>

            <Card className="border-l-4 border-l-purple-500">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Eventos del Año</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Calendar className="h-8 w-8 text-purple-500" />
                  <span className="text-3xl font-bold">{stats.eventos.total}</span>
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  {stats.eventos.porTipo.ENTRENAMIENTO} entrenamientos
                </p>
              </CardContent>
            </Card>

            <Card className="border-l-4 border-l-yellow-500">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Recaudación</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <DollarSign className="h-8 w-8 text-yellow-500" />
                  <span className="text-3xl font-bold">
                    ${stats.finanzas.totalRecaudado.toLocaleString()}
                  </span>
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  {stats.finanzas.cantidadPagos} pagos recibidos
                </p>
              </CardContent>
            </Card>
          </div>

          {/* Estadísticas de partidos y goleadores */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Resultados de partidos */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Trophy className="h-5 w-5 text-orange-500" />
                  Resultados de Partidos
                </CardTitle>
                <CardDescription>{stats.partidos.total} partidos jugados</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-3 gap-4 mb-6">
                  <div className="text-center p-4 bg-green-50 rounded-lg">
                    <p className="text-3xl font-bold text-green-600">{stats.partidos.victorias}</p>
                    <p className="text-sm text-gray-500">Victorias</p>
                  </div>
                  <div className="text-center p-4 bg-yellow-50 rounded-lg">
                    <p className="text-3xl font-bold text-yellow-600">{stats.partidos.empates}</p>
                    <p className="text-sm text-gray-500">Empates</p>
                  </div>
                  <div className="text-center p-4 bg-red-50 rounded-lg">
                    <p className="text-3xl font-bold text-red-600">{stats.partidos.derrotas}</p>
                    <p className="text-sm text-gray-500">Derrotas</p>
                  </div>
                </div>

                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600">Goles a Favor</span>
                    <span className="font-semibold text-green-600">+{stats.partidos.golesAFavor}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600">Goles en Contra</span>
                    <span className="font-semibold text-red-600">-{stats.partidos.golesEnContra}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600">Diferencia de Goles</span>
                    <span
                      className={`font-bold ${
                        stats.partidos.golesAFavor - stats.partidos.golesEnContra >= 0
                          ? 'text-green-600'
                          : 'text-red-600'
                      }`}
                    >
                      {stats.partidos.golesAFavor - stats.partidos.golesEnContra > 0 ? '+' : ''}
                      {stats.partidos.golesAFavor - stats.partidos.golesEnContra}
                    </span>
                  </div>
                  <hr />
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600">Tarjetas Amarillas</span>
                    <Badge variant="outline" className="bg-yellow-100 text-yellow-700">
                      {stats.partidos.tarjetasAmarillas}
                    </Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600">Tarjetas Rojas</span>
                    <Badge variant="outline" className="bg-red-100 text-red-700">
                      {stats.partidos.tarjetasRojas}
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Top Goleadores */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Award className="h-5 w-5 text-yellow-500" />
                  Top Goleadores {ano}
                </CardTitle>
                <CardDescription>Tabla de goleadores del año</CardDescription>
              </CardHeader>
              <CardContent>
                {stats.topGoleadores.length === 0 ? (
                  <p className="text-center text-gray-500 py-8">No hay goles registrados este año</p>
                ) : (
                  <div className="space-y-3">
                    {stats.topGoleadores.map((goleador, index) => (
                      <div
                        key={goleador.alumnoId}
                        className={`flex items-center justify-between p-3 rounded-lg ${
                          index === 0
                            ? 'bg-yellow-50 border border-yellow-200'
                            : index === 1
                            ? 'bg-gray-100'
                            : index === 2
                            ? 'bg-orange-50'
                            : 'bg-white'
                        }`}
                      >
                        <div className="flex items-center gap-3">
                          <span
                            className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                              index === 0
                                ? 'bg-yellow-500 text-white'
                                : index === 1
                                ? 'bg-gray-400 text-white'
                                : index === 2
                                ? 'bg-orange-400 text-white'
                                : 'bg-gray-200 text-gray-600'
                            }`}
                          >
                            {index + 1}
                          </span>
                          <div>
                            <p className="font-medium">{goleador.nombre}</p>
                            <p className="text-xs text-gray-500">Cat. {goleador.categoria}</p>
                          </div>
                        </div>
                        <span className="text-xl font-bold text-green-600">{goleador.goles}</span>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* Gráfico de eventos por mes */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="h-5 w-5 text-blue-500" />
                Eventos por Mes
              </CardTitle>
              <CardDescription>Distribución de eventos durante el año</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-end justify-between h-48 gap-2">
                {meses.map((mes, index) => {
                  const cantidad = stats.eventos.porMes[index + 1] || 0;
                  const altura = maxEventosMes > 0 ? (cantidad / maxEventosMes) * 100 : 0;
                  return (
                    <div key={mes} className="flex flex-col items-center flex-1">
                      <span className="text-xs font-medium mb-1">{cantidad}</span>
                      <div
                        className="w-full bg-blue-500 rounded-t transition-all"
                        style={{ height: `${Math.max(altura, 4)}%` }}
                      />
                      <span className="text-xs text-gray-500 mt-2">{mes}</span>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>

          {/* Más estadísticas */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Profesores</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Activity className="h-6 w-6 text-indigo-500" />
                  <span className="text-2xl font-bold">{stats.profesores.total}</span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Campeonatos Activos</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Trophy className="h-6 w-6 text-amber-500" />
                  <span className="text-2xl font-bold">{stats.campeonatos.activos}</span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Evaluaciones Físicas</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Target className="h-6 w-6 text-pink-500" />
                  <span className="text-2xl font-bold">{stats.evaluaciones.fisicas}</span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-gray-500">Evaluaciones Deportivas</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <Target className="h-6 w-6 text-cyan-500" />
                  <span className="text-2xl font-bold">{stats.evaluaciones.deportivas}</span>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Alumnos por categoría */}
          <Card>
            <CardHeader>
              <CardTitle>Alumnos por Categoría</CardTitle>
              <CardDescription>Distribución de alumnos según año de nacimiento</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                {stats.alumnos.porCategoria
                  .sort((a, b) => parseInt(b.categoria) - parseInt(a.categoria))
                  .map((cat) => (
                    <div
                      key={cat.categoria}
                      className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg text-center"
                    >
                      <p className="text-2xl font-bold text-blue-600">{cat.cantidad}</p>
                      <p className="text-sm text-gray-600">Cat. {cat.categoria}</p>
                    </div>
                  ))}
              </div>
            </CardContent>
          </Card>

          {/* Resumen de eventos por tipo */}
          <Card>
            <CardHeader>
              <CardTitle>Eventos por Tipo</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-500">Entrenamientos</p>
                      <p className="text-3xl font-bold text-green-600">
                        {stats.eventos.porTipo.ENTRENAMIENTO}
                      </p>
                    </div>
                    <Activity className="h-10 w-10 text-green-400" />
                  </div>
                </div>
                <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-500">Amistosos</p>
                      <p className="text-3xl font-bold text-blue-600">
                        {stats.eventos.porTipo.AMISTOSO}
                      </p>
                    </div>
                    <Users className="h-10 w-10 text-blue-400" />
                  </div>
                </div>
                <div className="p-4 bg-amber-50 rounded-lg border border-amber-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-500">Campeonatos</p>
                      <p className="text-3xl font-bold text-amber-600">
                        {stats.eventos.porTipo.CAMPEONATO}
                      </p>
                    </div>
                    <Trophy className="h-10 w-10 text-amber-400" />
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
