
"use client";

import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { signOut } from "next-auth/react";
import { 
  Users, 
  Building, 
  GraduationCap, 
  FileText, 
  Settings, 
  LogOut,
  BarChart3,
  Calendar,
  Image as ImageIcon
} from "lucide-react";
import Link from "next/link";

export default function AdminDashboardPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [stats, setStats] = useState({
    inscripciones: 0,
    escuelas: 0,
    instructores: 0,
    albums: 0,
  });

  useEffect(() => {
    if (status === "loading") return;
    
    if (!session?.user || session.user.rol !== 'admin') {
      router.push('/admin/login');
      return;
    }

    fetchStats();
  }, [session, status, router]);

  const fetchStats = async () => {
    try {
      const response = await fetch('/api/admin/stats');
      if (response.ok) {
        const data = await response.json();
        setStats(data);
      }
    } catch (error) {
      console.error('Error fetching stats:', error);
    }
  };

  if (status === "loading") {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">Cargando...</div>
      </div>
    );
  }

  if (!session?.user || session.user.rol !== 'admin') {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200">
        <div className="container-custom">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center space-x-4">
              <h1 className="heading-primary text-2xl text-[#0A2240]">
                Panel de Administración
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              <span className="text-sm text-gray-600">
                Bienvenido, {session.user.name || session.user.email}
              </span>
              <Button
                onClick={() => signOut()}
                variant="outline"
                size="sm"
                className="text-gray-600 hover:text-red-600"
              >
                <LogOut className="h-4 w-4 mr-2" />
                Cerrar Sesión
              </Button>
            </div>
          </div>
        </div>
      </header>

      <div className="container-custom py-8">
        {/* Stats Cards */}
        <div className="grid md:grid-cols-4 gap-6 mb-8">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Inscripciones</CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.inscripciones}</div>
              <p className="text-xs text-muted-foreground">
                Solicitudes de inscripción
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Escuelas</CardTitle>
              <Building className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.escuelas}</div>
              <p className="text-xs text-muted-foreground">
                Instituciones registradas
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Instructores</CardTitle>
              <GraduationCap className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.instructores}</div>
              <p className="text-xs text-muted-foreground">
                Instructores registrados
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Álbumes</CardTitle>
              <ImageIcon className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.albums}</div>
              <p className="text-xs text-muted-foreground">
                Galerías de fotos
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Management Sections */}
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {/* Inscripciones */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <FileText className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Gestión de Inscripciones</CardTitle>
              </div>
              <CardDescription>
                Ver, aprobar y gestionar todas las solicitudes de inscripción
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/inscripciones">Ver Inscripciones</Link>
              </Button>
            </CardContent>
          </Card>

          {/* Escuelas */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <Building className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Gestión de Escuelas</CardTitle>
              </div>
              <CardDescription>
                Administrar escuelas deportivas e instituciones registradas
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/escuelas">Ver Escuelas</Link>
              </Button>
            </CardContent>
          </Card>

          {/* Instructores */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <GraduationCap className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Gestión de Instructores</CardTitle>
              </div>
              <CardDescription>
                Administrar instructores y entrenadores deportivos
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/instructores">Ver Instructores</Link>
              </Button>
            </CardContent>
          </Card>

          {/* Galerías */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <ImageIcon className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Gestión de Galerías</CardTitle>
              </div>
              <CardDescription>
                Administrar álbumes y galerías de fotos
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/galerias">Ver Galerías</Link>
              </Button>
            </CardContent>
          </Card>

          {/* Contenido */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <Settings className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Gestión de Contenido</CardTitle>
              </div>
              <CardDescription>
                Editar textos y contenido del sitio web
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/contenido">Editar Contenido</Link>
              </Button>
            </CardContent>
          </Card>

          {/* Reportes */}
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardHeader>
              <div className="flex items-center space-x-2">
                <BarChart3 className="h-6 w-6 text-[#00B8D4]" />
                <CardTitle>Reportes y Estadísticas</CardTitle>
              </div>
              <CardDescription>
                Ver estadísticas detalladas y generar reportes
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild className="w-full" variant="primary">
                <Link href="/admin/reportes">Ver Reportes</Link>
              </Button>
            </CardContent>
          </Card>
        </div>

        {/* Quick Actions */}
        <div className="mt-8">
          <Card>
            <CardHeader>
              <CardTitle>Acciones Rápidas</CardTitle>
              <CardDescription>
                Accede a las funciones más utilizadas
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-4">
                <Button asChild variant="outline">
                  <Link href="/admin/inscripciones?filter=pendiente">
                    <FileText className="h-4 w-4 mr-2" />
                    Inscripciones Pendientes
                  </Link>
                </Button>
                <Button asChild variant="outline">
                  <Link href="/admin/escuelas?filter=no-verificada">
                    <Building className="h-4 w-4 mr-2" />
                    Escuelas Sin Verificar
                  </Link>
                </Button>
                <Button asChild variant="outline">
                  <Link href="/admin/galerias/nueva">
                    <ImageIcon className="h-4 w-4 mr-2" />
                    Nueva Galería
                  </Link>
                </Button>
                <Button asChild variant="outline">
                  <Link href="/" target="_blank">
                    <Calendar className="h-4 w-4 mr-2" />
                    Ver Sitio Web
                  </Link>
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
