'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  ArrowLeft, 
  FileText, 
  Download, 
  Eye,
  User,
  Users,
  Calendar,
  ClipboardList,
  DollarSign,
  Trophy,
  Activity,
  RefreshCw,
  Printer,
  FileSpreadsheet
} 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;
  };
}

export default function DocumentosPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  const [categorias, setCategorias] = useState<string[]>([]);
  const [reporteData, setReporteData] = useState<any>(null);
  const [filtros, setFiltros] = useState({
    alumnoId: '',
    categoria: '',
    mes: '',
    ano: new Date().getFullYear().toString(),
    tipoEvaluacion: 'ambas'
  });

  useEffect(() => {
    if (status === 'loading') return;
    if (!session?.user) {
      router.push('/auth/signin');
      return;
    }
    fetchAlumnos();
  }, [session, status, router]);

  const fetchAlumnos = async () => {
    try {
      const res = await fetch('/api/alumnos');
      const data = await res.json();
      if (data.success) {
        setAlumnos(data.alumnos);
        const cats = [...new Set(data.alumnos.map((a: Alumno) => a.categoria))];
        setCategorias(cats.sort() as string[]);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const generarReporteAlumno = async () => {
    if (!filtros.alumnoId) {
      toast.error('Seleccione un alumno');
      return;
    }
    
    setLoading(true);
    setReporteData(null);
    
    try {
      const res = await fetch(`/api/reportes/alumno?alumnoId=${filtros.alumnoId}`);
      const data = await res.json();
      
      if (data.success) {
        setReporteData({ tipo: 'alumno', data: data.reporte });
        toast.success('Reporte generado');
      } else {
        toast.error(data.error || 'Error generando reporte');
      }
    } catch (error) {
      toast.error('Error al generar reporte');
    } finally {
      setLoading(false);
    }
  };

  const generarReporteAsistencia = async () => {
    setLoading(true);
    setReporteData(null);
    
    try {
      let url = `/api/reportes/asistencia?ano=${filtros.ano}`;
      if (filtros.categoria) url += `&categoria=${filtros.categoria}`;
      if (filtros.mes) url += `&mes=${filtros.mes}`;
      
      const res = await fetch(url);
      const data = await res.json();
      
      if (data.success) {
        setReporteData({ tipo: 'asistencia', data: data.reporte });
        toast.success('Reporte generado');
      } else {
        toast.error(data.error || 'Error generando reporte');
      }
    } catch (error) {
      toast.error('Error al generar reporte');
    } finally {
      setLoading(false);
    }
  };

  const generarReporteEvaluaciones = async () => {
    setLoading(true);
    setReporteData(null);
    
    try {
      let url = `/api/reportes/evaluaciones?ano=${filtros.ano}`;
      if (filtros.categoria) url += `&categoria=${filtros.categoria}`;
      if (filtros.tipoEvaluacion !== 'ambas') url += `&tipo=${filtros.tipoEvaluacion}`;
      
      const res = await fetch(url);
      const data = await res.json();
      
      if (data.success) {
        setReporteData({ tipo: 'evaluaciones', data: data.reporte });
        toast.success('Reporte generado');
      } else {
        toast.error(data.error || 'Error generando reporte');
      }
    } catch (error) {
      toast.error('Error al generar reporte');
    } finally {
      setLoading(false);
    }
  };

  const imprimirReporte = () => {
    window.print();
  };

  const meses = [
    { value: '1', label: 'Enero' },
    { value: '2', label: 'Febrero' },
    { value: '3', label: 'Marzo' },
    { value: '4', label: 'Abril' },
    { value: '5', label: 'Mayo' },
    { value: '6', label: 'Junio' },
    { value: '7', label: 'Julio' },
    { value: '8', label: 'Agosto' },
    { value: '9', label: 'Septiembre' },
    { value: '10', label: 'Octubre' },
    { value: '11', label: 'Noviembre' },
    { value: '12', label: 'Diciembre' }
  ];

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={() => router.push('/dashboard')}>
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div>
              <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                <FileText className="h-6 w-6 text-blue-600" />
                Documentos y Reportes
              </h1>
              <p className="text-gray-600">Genera y descarga reportes de la escuela</p>
            </div>
          </div>
          {reporteData && (
            <Button onClick={imprimirReporte}>
              <Printer className="h-4 w-4 mr-2" />
              Imprimir
            </Button>
          )}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Panel de selección */}
          <div className="lg:col-span-1">
            <Tabs defaultValue="alumno" className="w-full">
              <TabsList className="grid grid-cols-3 w-full">
                <TabsTrigger value="alumno">
                  <User className="h-4 w-4" />
                </TabsTrigger>
                <TabsTrigger value="asistencia">
                  <ClipboardList className="h-4 w-4" />
                </TabsTrigger>
                <TabsTrigger value="evaluaciones">
                  <Activity className="h-4 w-4" />
                </TabsTrigger>
              </TabsList>

              {/* Reporte de Alumno */}
              <TabsContent value="alumno">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <User className="h-5 w-5 text-blue-600" />
                      Ficha de Alumno
                    </CardTitle>
                    <CardDescription>
                      Reporte completo con datos personales, evaluaciones y progreso
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <Label>Seleccionar Alumno</Label>
                      <Select 
                        value={filtros.alumnoId} 
                        onValueChange={(v) => setFiltros({...filtros, alumnoId: v})}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Buscar alumno..." />
                        </SelectTrigger>
                        <SelectContent>
                          {alumnos.map(a => (
                            <SelectItem key={a.id} value={a.id}>
                              {a.usuario.apellidos}, {a.usuario.nombres} ({a.categoria})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <Button 
                      onClick={generarReporteAlumno} 
                      disabled={loading || !filtros.alumnoId}
                      className="w-full"
                    >
                      {loading ? <RefreshCw className="h-4 w-4 animate-spin mr-2" /> : <FileText className="h-4 w-4 mr-2" />}
                      Generar Reporte
                    </Button>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* Reporte de Asistencia */}
              <TabsContent value="asistencia">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <ClipboardList className="h-5 w-5 text-green-600" />
                      Reporte de Asistencia
                    </CardTitle>
                    <CardDescription>
                      Estadísticas de asistencia por período y categoría
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <Label>Año</Label>
                      <Select 
                        value={filtros.ano} 
                        onValueChange={(v) => setFiltros({...filtros, ano: v})}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {[2024, 2025, 2026].map(a => (
                            <SelectItem key={a} value={a.toString()}>{a}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Mes (opcional)</Label>
                      <Select 
                        value={filtros.mes} 
                        onValueChange={(v) => setFiltros({...filtros, mes: v})}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Todos los meses" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="">Todos los meses</SelectItem>
                          {meses.map(m => (
                            <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Categoría (opcional)</Label>
                      <Select 
                        value={filtros.categoria} 
                        onValueChange={(v) => setFiltros({...filtros, categoria: v})}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Todas las categorías" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="">Todas</SelectItem>
                          {categorias.map(c => (
                            <SelectItem key={c} value={c}>{c}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <Button 
                      onClick={generarReporteAsistencia} 
                      disabled={loading}
                      className="w-full"
                    >
                      {loading ? <RefreshCw className="h-4 w-4 animate-spin mr-2" /> : <FileText className="h-4 w-4 mr-2" />}
                      Generar Reporte
                    </Button>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* Reporte de Evaluaciones */}
              <TabsContent value="evaluaciones">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Activity className="h-5 w-5 text-purple-600" />
                      Reporte de Evaluaciones
                    </CardTitle>
                    <CardDescription>
                      Resumen de evaluaciones físicas y deportivas
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <Label>Año</Label>
                      <Select 
                        value={filtros.ano} 
                        onValueChange={(v) => setFiltros({...filtros, ano: v})}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {[2024, 2025, 2026].map(a => (
                            <SelectItem key={a} value={a.toString()}>{a}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Tipo de Evaluación</Label>
                      <Select 
                        value={filtros.tipoEvaluacion} 
                        onValueChange={(v) => setFiltros({...filtros, tipoEvaluacion: v})}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="ambas">Ambas</SelectItem>
                          <SelectItem value="fisica">Solo Físicas</SelectItem>
                          <SelectItem value="deportiva">Solo Deportivas</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Categoría (opcional)</Label>
                      <Select 
                        value={filtros.categoria} 
                        onValueChange={(v) => setFiltros({...filtros, categoria: v})}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Todas las categorías" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="">Todas</SelectItem>
                          {categorias.map(c => (
                            <SelectItem key={c} value={c}>{c}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <Button 
                      onClick={generarReporteEvaluaciones} 
                      disabled={loading}
                      className="w-full"
                    >
                      {loading ? <RefreshCw className="h-4 w-4 animate-spin mr-2" /> : <FileText className="h-4 w-4 mr-2" />}
                      Generar Reporte
                    </Button>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>

          {/* Vista previa del reporte */}
          <div className="lg:col-span-2">
            <Card className="min-h-[600px]">
              <CardHeader>
                <CardTitle>Vista Previa del Reporte</CardTitle>
              </CardHeader>
              <CardContent>
                {!reporteData ? (
                  <div className="flex flex-col items-center justify-center h-96 text-gray-400">
                    <FileText className="h-16 w-16 mb-4" />
                    <p>Seleccione un tipo de reporte y genérelo</p>
                  </div>
                ) : (
                  <div className="print:p-8" id="reporte-contenido">
                    {reporteData.tipo === 'alumno' && <ReporteAlumnoView data={reporteData.data} />}
                    {reporteData.tipo === 'asistencia' && <ReporteAsistenciaView data={reporteData.data} />}
                    {reporteData.tipo === 'evaluaciones' && <ReporteEvaluacionesView data={reporteData.data} />}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

// Componentes de vista de reportes
function ReporteAlumnoView({ data }: { data: any }) {
  return (
    <div className="space-y-6">
      <div className="text-center border-b pb-4">
        <h2 className="text-2xl font-bold">{data.escuela.nombre}</h2>
        <h3 className="text-lg text-gray-600">Ficha del Alumno</h3>
      </div>
      
      <div className="grid grid-cols-2 gap-6">
        <div>
          <h4 className="font-semibold text-blue-600 mb-2">Datos Personales</h4>
          <div className="space-y-1 text-sm">
            <p><strong>Nombre:</strong> {data.datosPersonales.nombres} {data.datosPersonales.apellidos}</p>
            <p><strong>RUT:</strong> {data.datosPersonales.rut}</p>
            <p><strong>Categoría:</strong> {data.datosPersonales.categoria}</p>
            <p><strong>Posición:</strong> {data.datosPersonales.posicionPreferida || 'No definida'}</p>
            <p><strong>Pie Hábil:</strong> {data.datosPersonales.pieHabil || 'No definido'}</p>
          </div>
        </div>
        
        <div>
          <h4 className="font-semibold text-blue-600 mb-2">Estadísticas</h4>
          <div className="space-y-1 text-sm">
            <p><strong>Asistencia:</strong> {data.estadisticas.porcentajeAsistencia}%</p>
            <p><strong>Eventos asistidos:</strong> {data.estadisticas.asistenciasPresente} de {data.estadisticas.totalAsistencias}</p>
            <p><strong>Objetivos completados:</strong> {data.estadisticas.objetivosCompletados} de {data.estadisticas.totalObjetivos}</p>
          </div>
        </div>
      </div>

      {data.ultimaEvaluacionDeportiva && (
        <div>
          <h4 className="font-semibold text-purple-600 mb-2">Última Evaluación Deportiva</h4>
          <div className="grid grid-cols-6 gap-2 text-center text-sm">
            {['Técnica', 'Fuerza', 'Ataque', 'Defensa', 'Resistencia', 'Velocidad'].map((label, i) => {
              const keys = ['tecnica', 'fuerza', 'ataque', 'defensa', 'resistencia', 'velocidad'];
              return (
                <div key={label} className="bg-gray-100 rounded p-2">
                  <div className="text-xs text-gray-500">{label}</div>
                  <div className="font-bold">{data.ultimaEvaluacionDeportiva[keys[i]]}/5</div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {data.apoderado && (
        <div>
          <h4 className="font-semibold text-green-600 mb-2">Apoderado</h4>
          <p className="text-sm">
            {data.apoderado.nombre} ({data.apoderado.relacion}) - Tel: {data.apoderado.telefono}
          </p>
        </div>
      )}
    </div>
  );
}

function ReporteAsistenciaView({ data }: { data: any }) {
  return (
    <div className="space-y-6">
      <div className="text-center border-b pb-4">
        <h2 className="text-xl font-bold">Reporte de Asistencia</h2>
        <p className="text-gray-600">
          Año {data.periodo.ano} {data.periodo.mes ? `- Mes ${data.periodo.mes}` : ''}
          {data.periodo.categoria !== 'Todas' && ` - Categoría ${data.periodo.categoria}`}
        </p>
      </div>

      <div className="grid grid-cols-4 gap-4 text-center">
        <div className="bg-blue-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-blue-600">{data.resumen.totalAlumnos}</div>
          <div className="text-xs text-gray-600">Alumnos</div>
        </div>
        <div className="bg-green-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-green-600">{data.resumen.totalPresentes}</div>
          <div className="text-xs text-gray-600">Presentes</div>
        </div>
        <div className="bg-red-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-red-600">{data.resumen.totalAusentes}</div>
          <div className="text-xs text-gray-600">Ausentes</div>
        </div>
        <div className="bg-purple-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-purple-600">{data.resumen.promedioAsistencia}%</div>
          <div className="text-xs text-gray-600">Promedio</div>
        </div>
      </div>

      <div>
        <h4 className="font-semibold mb-2">Detalle por Alumno</h4>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-100">
              <tr>
                <th className="text-left p-2">Alumno</th>
                <th className="text-center p-2">Cat.</th>
                <th className="text-center p-2">Presente</th>
                <th className="text-center p-2">Ausente</th>
                <th className="text-center p-2">%</th>
              </tr>
            </thead>
            <tbody>
              {data.detallePorAlumno.slice(0, 15).map((alumno: any, i: number) => (
                <tr key={i} className="border-b">
                  <td className="p-2">{alumno.apellidos}, {alumno.nombres}</td>
                  <td className="text-center p-2">{alumno.categoria}</td>
                  <td className="text-center p-2 text-green-600">{alumno.presentes}</td>
                  <td className="text-center p-2 text-red-600">{alumno.ausentes}</td>
                  <td className="text-center p-2 font-semibold">{alumno.porcentaje}%</td>
                </tr>
              ))}
            </tbody>
          </table>
          {data.detallePorAlumno.length > 15 && (
            <p className="text-center text-gray-500 text-sm mt-2">
              ... y {data.detallePorAlumno.length - 15} alumnos más
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

function ReporteEvaluacionesView({ data }: { data: any }) {
  return (
    <div className="space-y-6">
      <div className="text-center border-b pb-4">
        <h2 className="text-xl font-bold">Reporte de Evaluaciones</h2>
        <p className="text-gray-600">
          Año {data.periodo.ano}
          {data.periodo.categoria !== 'Todas' && ` - Categoría ${data.periodo.categoria}`}
        </p>
      </div>

      <div className="grid grid-cols-3 gap-4 text-center">
        <div className="bg-blue-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-blue-600">{data.resumen.totalAlumnos}</div>
          <div className="text-xs text-gray-600">Total Alumnos</div>
        </div>
        <div className="bg-green-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-green-600">{data.resumen.alumnosConEvalFisica}</div>
          <div className="text-xs text-gray-600">Con Eval. Física</div>
        </div>
        <div className="bg-purple-50 rounded-lg p-3">
          <div className="text-2xl font-bold text-purple-600">{data.resumen.alumnosConEvalDeportiva}</div>
          <div className="text-xs text-gray-600">Con Eval. Deportiva</div>
        </div>
      </div>

      {data.resumen.promediosDeportivos && (
        <div>
          <h4 className="font-semibold mb-2">Promedios Deportivos Generales</h4>
          <div className="grid grid-cols-6 gap-2 text-center text-sm">
            {Object.entries(data.resumen.promediosDeportivos).map(([key, value]) => (
              <div key={key} className="bg-gray-100 rounded p-2">
                <div className="text-xs text-gray-500 capitalize">{key}</div>
                <div className="font-bold">{value as string}/5</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {data.evaluacionesDeportivas && (
        <div>
          <h4 className="font-semibold mb-2">Evaluaciones Deportivas</h4>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="text-left p-2">Alumno</th>
                  <th className="text-center p-2">Evals</th>
                  <th className="text-center p-2">Puntaje</th>
                  <th className="text-center p-2">Posiciones</th>
                </tr>
              </thead>
              <tbody>
                {data.evaluacionesDeportivas
                  .filter((e: any) => e.ultimaEvaluacion)
                  .slice(0, 10)
                  .map((eval_: any, i: number) => (
                    <tr key={i} className="border-b">
                      <td className="p-2">{eval_.nombre}</td>
                      <td className="text-center p-2">{eval_.cantidadEvaluaciones}</td>
                      <td className="text-center p-2 font-semibold">
                        {eval_.ultimaEvaluacion?.puntajeTotal?.toFixed(1)}
                      </td>
                      <td className="text-center p-2 text-xs">
                        {eval_.ultimaEvaluacion?.posicionesPreferentes?.slice(0, 2).join(', ')}
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
