'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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { 
  ArrowLeft, 
  DollarSign, 
  TrendingUp, 
  TrendingDown, 
  Users, 
  Plus,
  CreditCard,
  Receipt,
  PieChart,
  Calendar,
  Trash2
} from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

interface Pago {
  id: string;
  alumnoId: string;
  fecha: string;
  monto: number;
  concepto: string;
  metodoPago: string;
  alumno: {
    usuario: {
      nombres: string;
      apellidos: string;
      rut: string;
    };
  };
}

interface ResumenFinanciero {
  ano: number;
  resumen: {
    totalIngresos: number;
    totalPagosAlumnos: number;
    ingresosOtros: number;
    totalEgresos: number;
    balance: number;
    cantidadPagos: number;
    alumnosConPagos: number;
    totalAlumnos: number;
    porcentajeAlumnosPagando: number;
  };
  pagosPorMes: number[];
  pagosPorConcepto: { concepto: string; total: number }[];
}

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

const METODOS_PAGO: { [key: string]: string } = {
  'EFECTIVO': 'Efectivo',
  'TRANSFERENCIA': 'Transferencia',
  'TARJETA': 'Tarjeta',
  'CHEQUE': 'Cheque'
};

export default function FinanzasPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [pagos, setPagos] = useState<Pago[]>([]);
  const [resumen, setResumen] = useState<ResumenFinanciero | null>(null);
  const [loading, setLoading] = useState(true);
  const [anoSeleccionado, setAnoSeleccionado] = useState(new Date().getFullYear().toString());
  const [mesSeleccionado, setMesSeleccionado] = useState<string>('todos');

  const userRol = (session?.user as any)?.rol;
  const esCoordinador = userRol === 'COORDINADOR';
  const puedeGestionar = ['COORDINADOR', 'PROFESOR'].includes(userRol);

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

  useEffect(() => {
    if (session) {
      fetchData();
    }
  }, [session, anoSeleccionado, mesSeleccionado]);

  const fetchData = async () => {
    setLoading(true);
    try {
      // Fetch resumen
      const resumenRes = await fetch(`/api/finanzas/resumen?ano=${anoSeleccionado}`);
      if (resumenRes.ok) {
        const resumenData = await resumenRes.json();
        setResumen(resumenData);
      }

      // Fetch pagos
      let pagosUrl = `/api/pagos?ano=${anoSeleccionado}`;
      if (mesSeleccionado !== 'todos') {
        pagosUrl += `&mes=${mesSeleccionado}`;
      }
      const pagosRes = await fetch(pagosUrl);
      if (pagosRes.ok) {
        const pagosData = await pagosRes.json();
        setPagos(pagosData.pagos || []);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Error al cargar datos financieros');
    } finally {
      setLoading(false);
    }
  };

  const handleDeletePago = async (id: string) => {
    if (!confirm('¿Estás seguro de eliminar este pago?')) return;

    try {
      const res = await fetch(`/api/pagos/${id}`, { method: 'DELETE' });
      if (res.ok) {
        toast.success('Pago eliminado correctamente');
        fetchData();
      } else {
        const data = await res.json();
        toast.error(data.error || 'Error al eliminar pago');
      }
    } catch (error) {
      toast.error('Error al eliminar pago');
    }
  };

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

  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-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Button variant="ghost" onClick={() => router.push('/dashboard')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Volver al Dashboard
            </Button>
          </div>
          {puedeGestionar && (
            <div className="flex gap-2">
              <Button onClick={() => router.push('/dashboard/finanzas/pagos/nuevo')} className="bg-green-600 hover:bg-green-700">
                <Plus className="w-4 h-4 mr-2" />
                Registrar Pago
              </Button>
              {esCoordinador && (
                <Button onClick={() => router.push('/dashboard/finanzas/movimientos/nuevo')} variant="outline">
                  <Receipt className="w-4 h-4 mr-2" />
                  Nuevo Movimiento
                </Button>
              )}
            </div>
          )}
        </div>

        {/* Título y filtros */}
        <div className="flex flex-col md:flex-row md:items-center justify-between mb-6 gap-4">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-2">
              <DollarSign className="w-8 h-8 text-green-600" />
              Gestión Financiera
            </h1>
            <p className="text-gray-600">Control de pagos e ingresos de la escuela</p>
          </div>
          <div className="flex gap-2">
            <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>
            <Select value={mesSeleccionado} onValueChange={setMesSeleccionado}>
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="Mes" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="todos">Todos los meses</SelectItem>
                {MESES.map((mes, i) => (
                  <SelectItem key={i} value={(i + 1).toString()}>{mes}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Tarjetas de resumen */}
        {resumen && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <Card className="border-l-4 border-l-green-500">
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-500">Total Ingresos</p>
                    <p className="text-2xl font-bold text-green-600">{formatMoney(resumen.resumen.totalIngresos)}</p>
                  </div>
                  <TrendingUp className="w-10 h-10 text-green-500 opacity-50" />
                </div>
              </CardContent>
            </Card>

            <Card className="border-l-4 border-l-blue-500">
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-500">Pagos de Alumnos</p>
                    <p className="text-2xl font-bold text-blue-600">{formatMoney(resumen.resumen.totalPagosAlumnos)}</p>
                  </div>
                  <CreditCard className="w-10 h-10 text-blue-500 opacity-50" />
                </div>
              </CardContent>
            </Card>

            <Card className="border-l-4 border-l-red-500">
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-500">Total Egresos</p>
                    <p className="text-2xl font-bold text-red-600">{formatMoney(resumen.resumen.totalEgresos)}</p>
                  </div>
                  <TrendingDown className="w-10 h-10 text-red-500 opacity-50" />
                </div>
              </CardContent>
            </Card>

            <Card className={`border-l-4 ${resumen.resumen.balance >= 0 ? 'border-l-emerald-500' : 'border-l-orange-500'}`}>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-500">Balance</p>
                    <p className={`text-2xl font-bold ${resumen.resumen.balance >= 0 ? 'text-emerald-600' : 'text-orange-600'}`}>
                      {formatMoney(resumen.resumen.balance)}
                    </p>
                  </div>
                  <PieChart className="w-10 h-10 text-gray-400 opacity-50" />
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Estadísticas de alumnos */}
        {resumen && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-blue-100 rounded-full">
                    <Users className="w-6 h-6 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Alumnos Activos</p>
                    <p className="text-xl font-bold">{resumen.resumen.totalAlumnos}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-green-100 rounded-full">
                    <CreditCard className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Alumnos con Pagos</p>
                    <p className="text-xl font-bold">{resumen.resumen.alumnosConPagos}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-purple-100 rounded-full">
                    <Receipt className="w-6 h-6 text-purple-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Total de Pagos</p>
                    <p className="text-xl font-bold">{resumen.resumen.cantidadPagos}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Gráfico de barras simple con pagos por mes */}
        {resumen && (
          <Card className="mb-6">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Calendar className="w-5 h-5" />
                Pagos por Mes - {anoSeleccionado}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-end justify-between gap-2 h-48">
                {resumen.pagosPorMes.map((monto, i) => {
                  const maxMonto = Math.max(...resumen.pagosPorMes, 1);
                  const altura = (monto / maxMonto) * 100;
                  return (
                    <div key={i} className="flex-1 flex flex-col items-center">
                      <div 
                        className="w-full bg-green-500 rounded-t transition-all duration-300 hover:bg-green-600"
                        style={{ height: `${Math.max(altura, 2)}%` }}
                        title={formatMoney(monto)}
                      ></div>
                      <span className="text-xs text-gray-500 mt-1">{MESES[i]}</span>
                      <span className="text-xs font-medium">{monto > 0 ? formatMoney(monto).replace('CLP', '').trim() : '-'}</span>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Pagos por concepto */}
        {resumen && resumen.pagosPorConcepto.length > 0 && (
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>Pagos por Concepto</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {resumen.pagosPorConcepto.slice(0, 5).map((item, i) => {
                  const maxTotal = resumen.pagosPorConcepto[0]?.total || 1;
                  const porcentaje = (item.total / maxTotal) * 100;
                  return (
                    <div key={i}>
                      <div className="flex justify-between text-sm mb-1">
                        <span className="font-medium">{item.concepto}</span>
                        <span className="text-gray-600">{formatMoney(item.total)}</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                          style={{ width: `${porcentaje}%` }}
                        ></div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Tabla de pagos recientes */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>Pagos Recientes</span>
              <Button variant="outline" size="sm" onClick={() => router.push('/dashboard/finanzas/estado-cuenta')}>
                Ver Estado de Cuenta
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {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 período</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-3 px-2">Fecha</th>
                      <th className="text-left py-3 px-2">Alumno</th>
                      <th className="text-left py-3 px-2">Concepto</th>
                      <th className="text-left py-3 px-2">Método</th>
                      <th className="text-right py-3 px-2">Monto</th>
                      {esCoordinador && <th className="text-center py-3 px-2">Acciones</th>}
                    </tr>
                  </thead>
                  <tbody>
                    {pagos.slice(0, 20).map((pago) => (
                      <tr key={pago.id} className="border-b hover:bg-gray-50">
                        <td className="py-3 px-2">
                          {format(new Date(pago.fecha), 'dd/MM/yyyy', { locale: es })}
                        </td>
                        <td className="py-3 px-2">
                          <div>
                            <p className="font-medium">{pago.alumno.usuario.nombres} {pago.alumno.usuario.apellidos}</p>
                            <p className="text-xs text-gray-500">{pago.alumno.usuario.rut}</p>
                          </div>
                        </td>
                        <td className="py-3 px-2">
                          <Badge variant="outline">{pago.concepto}</Badge>
                        </td>
                        <td className="py-3 px-2">
                          {METODOS_PAGO[pago.metodoPago] || pago.metodoPago}
                        </td>
                        <td className="py-3 px-2 text-right font-medium text-green-600">
                          {formatMoney(pago.monto)}
                        </td>
                        {esCoordinador && (
                          <td className="py-3 px-2 text-center">
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => handleDeletePago(pago.id)}
                              className="text-red-500 hover:text-red-700 hover:bg-red-50"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
