'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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { ArrowLeft, Plus, Search, Pencil, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

interface Alumno {
  id: string;
  usuario: {
    rut: string;
    nombres: string;
    apellidos: string;
    email: string | null;
  };
  fechaNacimiento: string;
  categoria: {
    nombre: string;
  } | null;
  apoderado: {
    nombres: string;
    telefono: string;
  } | null;
}

export default function AlumnosPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [alumnoToDelete, setAlumnoToDelete] = useState<string | null>(null);

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

  useEffect(() => {
    fetchAlumnos();
  }, []);

  const fetchAlumnos = async () => {
    try {
      const response = await fetch('/api/alumnos');
      if (response.ok) {
        const data = await response.json();
        setAlumnos(data.alumnos || []);
      } else {
        toast.error('Error al cargar los alumnos');
      }
    } catch (error) {
      toast.error('Error de conexión');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!alumnoToDelete) return;

    try {
      const response = await fetch(`/api/alumnos/${alumnoToDelete}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        toast.success('Alumno eliminado exitosamente');
        fetchAlumnos();
      } else {
        toast.error('Error al eliminar el alumno');
      }
    } catch (error) {
      toast.error('Error de conexión');
    } finally {
      setDeleteDialogOpen(false);
      setAlumnoToDelete(null);
    }
  };

  const filteredAlumnos = alumnos.filter((alumno) => {
    const searchLower = searchTerm.toLowerCase();
    return (
      alumno.usuario.nombres.toLowerCase().includes(searchLower) ||
      alumno.usuario.apellidos.toLowerCase().includes(searchLower) ||
      alumno.usuario.rut.toLowerCase().includes(searchLower)
    );
  });

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

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => router.push('/dashboard')}
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              Volver al Dashboard
            </Button>
          </div>
        </div>
      </header>

      {/* Content */}
      <div className="max-w-7xl mx-auto px-4 py-8">
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-2xl">Gestión de Alumnos</CardTitle>
                <CardDescription>
                  Administra los alumnos de la escuela
                </CardDescription>
              </div>
              <Button onClick={() => router.push('/dashboard/alumnos/nuevo')}>
                <Plus className="w-4 h-4 mr-2" />
                Nuevo Alumno
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {/* Search */}
            <div className="mb-6">
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="Buscar por nombre, apellido o RUT..."
                  className="pl-10"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>

            {/* Table */}
            <div className="border rounded-lg">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>RUT</TableHead>
                    <TableHead>Nombre</TableHead>
                    <TableHead>Apellido</TableHead>
                    <TableHead>Categoría</TableHead>
                    <TableHead>Apoderado</TableHead>
                    <TableHead>Teléfono</TableHead>
                    <TableHead className="text-right">Acciones</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredAlumnos.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8">
                        {searchTerm
                          ? 'No se encontraron alumnos'
                          : 'No hay alumnos registrados'}
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredAlumnos.map((alumno) => (
                      <TableRow key={alumno.id}>
                        <TableCell className="font-medium">
                          {alumno.usuario.rut}
                        </TableCell>
                        <TableCell>{alumno.usuario.nombres}</TableCell>
                        <TableCell>{alumno.usuario.apellidos}</TableCell>
                        <TableCell>
                          {alumno.categoria?.nombre || 'Sin categoría'}
                        </TableCell>
                        <TableCell>
                          {alumno.apoderado?.nombres || 'N/A'}
                        </TableCell>
                        <TableCell>
                          {alumno.apoderado?.telefono || 'N/A'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() =>
                                router.push(`/dashboard/perfil-alumno?id=${alumno.id}`)
                              }
                              title="Ver/Editar perfil"
                            >
                              <Pencil className="w-4 h-4 text-blue-600" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setAlumnoToDelete(alumno.id);
                                setDeleteDialogOpen(true);
                              }}
                              title="Eliminar alumno"
                            >
                              <Trash2 className="w-4 h-4 text-red-600" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            {/* Summary */}
            <div className="mt-4 text-sm text-gray-600">
              Mostrando {filteredAlumnos.length} de {alumnos.length} alumnos
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>¿Estás seguro?</AlertDialogTitle>
            <AlertDialogDescription>
              Esta acción no se puede deshacer. Esto eliminará permanentemente el
              registro del alumno.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancelar</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              Eliminar
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
