'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { 
  ArrowLeft, 
  Search,
  User,
  DollarSign,
  Calendar,
  CreditCard,
  FileText
} from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

interface Alumno {
  id: string;
  categoria: string;
  usuario: {
    nombres: string;
    apellidos: string;
    rut: string;
    email?: string;
    telefono?: string;
  };
}

interface Pago {
  id: string;
  fecha: string;
  monto: number;
  concepto: string;
  metodoPago: string;
}

export default function EstadoCuentaPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  const [alumnoSeleccionado, setAlumnoSeleccionado] = useState<Alumno | null>(null);
  const [pagos, setPagos] = useState<Pago[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingPagos, setLoadingPagos] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [anoSeleccionado, setAnoSeleccionado] = useState(new Date().getFullYear().toString());

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

  const fetchAlumnos = async () => {
    try {
      const res = await fetch('/api/alumnos');
      if (res.ok) {
        const data = await res.json();
        setAlumnos(data.alumnos || []);
      }
    } catch (error) {
      console.error('Error fetching alumnos:', error);
      toast.error('Error al cargar alumnos');
    } finally {
      setLoading(false);
    }
  };

  const fetchPagosAlumno = async (alumnoId: string) => {
    setLoadingPagos(true);
    try {
      const res = await fetch(`/api/pagos?alumnoId=${alumnoId}&ano=${anoSeleccionado}`);
      if (res.ok) {
        const data = await res.json();
        setPagos(data.pagos || []);
      }
    } catch (error) {
      console.error('Error fetching pagos:', error);
      toast.error('Error al cargar pagos');
    } finally {
      setLoadingPagos(false);
    }
  };

  const handleSelectAlumno = (alumno: Alumno) => {
    setAlumnoSeleccionado(alumno);
    fetchPagosAlumno(alumno.id);
  };

  useEffect(() => {
    if (alumnoSeleccionado) {
      fetchPagosAlumno(alumnoSeleccionado.id);
    }
  }, [anoSeleccionado]);

  const formatMoney = (amount: number) => {
    return new Intl.NumberFormat('es-CL', {
      style: 'currency',
      currency: 'CLP'
    }).format(amount);
  };

  const filteredAlumnos = alumnos.filter(a => {
    const fullName = `${a.usuario.nombres} ${a.usuario.apellidos}`.toLowerCase();
    const rut = a.usuario.rut.toLowerCase();
    const search = searchTerm.toLowerCase();
    return fullName.includes(search) || rut.includes(search);
  });

  const totalPagado = pagos.reduce((sum, p) => sum + p.monto, 0);

  // Agrupar pagos por mes
  const pagosPorMes: { [key: string]: Pago[] } = {};
  pagos.forEach(pago => {
    const mes = format(new Date(pago.fecha), 'MMMM yyyy', { locale: es });
    if (!pagosPorMes[mes]) pagosPorMes[mes] = [];
    pagosPorMes[mes].push(pago);
  });

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

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="flex items-center gap-4 mb-6">
          <Button variant="ghost" onClick={() => router.push('/dashboard/finanzas')}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Volver a Finanzas
          </Button>
        </div>

        <h1 className="text-3xl font-bold text-gray-900 mb-6 flex items-center gap-2">
          <FileText className="w-8 h-8 text-green-600" />
          Estado de Cuenta por Alumno
        </h1>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Panel de búsqueda de alumnos */}
          <Card className="lg:col-span-1">
            <CardHeader>
              <CardTitle className="text-lg">Seleccionar Alumno</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="relative mb-4">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="Buscar por nombre o RUT..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              <div className="space-y-2 max-h-[500px] overflow-y-auto">
                {filteredAlumnos.map((alumno) => (
                  <button
                    key={alumno.id}
                    onClick={() => handleSelectAlumno(alumno)}
                    className={`w-full text-left p-3 rounded-lg border transition-colors ${
                      alumnoSeleccionado?.id === alumno.id
                        ? 'bg-green-50 border-green-300'
                        : 'hover:bg-gray-50 border-gray-200'
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                        <User className="w-5 h-5 text-blue-600" />
                      </div>
                      <div>
                        <p className="font-medium">{alumno.usuario.nombres} {alumno.usuario.apellidos}</p>
                        <p className="text-sm text-gray-500">{alumno.usuario.rut} • Cat. {alumno.categoria}</p>
                      </div>
                    </div>
                  </button>
                ))}
                {filteredAlumnos.length === 0 && (
                  <p className="text-center text-gray-500 py-4">No se encontraron alumnos</p>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Panel de estado de cuenta */}
          <div className="lg:col-span-2 space-y-6">
            {!alumnoSeleccionado ? (
              <Card>
                <CardContent className="py-16 text-center">
                  <User className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                  <h3 className="text-lg font-medium text-gray-500">Selecciona un alumno</h3>
                  <p className="text-gray-400">Para ver su estado de cuenta</p>
                </CardContent>
              </Card>
            ) : (
              <>
                {/* Información del alumno */}
                <Card className="bg-gradient-to-r from-blue-50 to-green-50">
                  <CardContent className="pt-6">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-4">
                        <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center">
                          <User className="w-8 h-8 text-blue-600" />
                        </div>
                        <div>
                          <h2 className="text-xl font-bold">
                            {alumnoSeleccionado.usuario.nombres} {alumnoSeleccionado.usuario.apellidos}
                          </h2>
                          <p className="text-gray-600">RUT: {alumnoSeleccionado.usuario.rut}</p>
                          <Badge variant="outline" className="mt-1">Categoría {alumnoSeleccionado.categoria}</Badge>
                        </div>
                      </div>
                      <Select value={anoSeleccionado} onValueChange={setAnoSeleccionado}>
                        <SelectTrigger className="w-[120px]">
                          <SelectValue placeholder="Año" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="2024">2024</SelectItem>
                          <SelectItem value="2025">2025</SelectItem>
                          <SelectItem value="2026">2026</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>

                {/* Resumen */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <Card className="border-l-4 border-l-green-500">
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-3">
                        <DollarSign className="w-8 h-8 text-green-500" />
                        <div>
                          <p className="text-sm text-gray-500">Total Pagado</p>
                          <p className="text-xl font-bold text-green-600">{formatMoney(totalPagado)}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                  <Card className="border-l-4 border-l-blue-500">
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-3">
                        <CreditCard className="w-8 h-8 text-blue-500" />
                        <div>
                          <p className="text-sm text-gray-500">Nº de Pagos</p>
                          <p className="text-xl font-bold">{pagos.length}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                  <Card className="border-l-4 border-l-purple-500">
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-3">
                        <Calendar className="w-8 h-8 text-purple-500" />
                        <div>
                          <p className="text-sm text-gray-500">Año</p>
                          <p className="text-xl font-bold">{anoSeleccionado}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* Historial de pagos */}
                <Card>
                  <CardHeader>
                    <CardTitle>Historial de Pagos</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {loadingPagos ? (
                      <div className="text-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600 mx-auto"></div>
                      </div>
                    ) : pagos.length === 0 ? (
                      <div className="text-center py-8 text-gray-500">
                        <CreditCard className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No hay pagos registrados para este año</p>
                      </div>
                    ) : (
                      <div className="space-y-6">
                        {Object.entries(pagosPorMes).map(([mes, pagosMes]) => (
                          <div key={mes}>
                            <h4 className="font-medium text-gray-700 mb-3 capitalize flex items-center gap-2">
                              <Calendar className="w-4 h-4" />
                              {mes}
                              <span className="text-sm text-gray-500 font-normal">
                                ({pagosMes.length} pago{pagosMes.length > 1 ? 's' : ''})
                              </span>
                            </h4>
                            <div className="space-y-2">
                              {pagosMes.map((pago) => (
                                <div key={pago.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                  <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                                      <DollarSign className="w-5 h-5 text-green-600" />
                                    </div>
                                    <div>
                                      <p className="font-medium">{pago.concepto}</p>
                                      <p className="text-sm text-gray-500">
                                        {format(new Date(pago.fecha), 'dd/MM/yyyy')} • {pago.metodoPago}
                                      </p>
                                    </div>
                                  </div>
                                  <p className="font-bold text-green-600">{formatMoney(pago.monto)}</p>
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
