import pool from '@/lib/db';
import { CreditCard, TrendingUp, ArrowUpRight, ArrowDownRight, Clock, Plus } from 'lucide-react';

async function getStats() {
    try {
        const [cobros]: any = await pool.query('SELECT SUM(importefinal) as total FROM cobros WHERE pagado = 1');
        const [pendientes]: any = await pool.query('SELECT SUM(importefinal) as total FROM cobros WHERE pagado = 0');
        return {
            recaudado: cobros[0].total || 0,
            pendiente: pendientes[0].total || 0
        };
    } catch (error) {
        return { recaudado: 0, pendiente: 0 };
    }
}

async function getRecentCobros() {
    try {
        const [rows]: any = await pool.query(`
      SELECT c.*, a.nombre_completo 
      FROM cobros c 
      JOIN alumnos a ON c.ida = a.id 
      ORDER BY c.fecharecibo DESC 
      LIMIT 10
    `);
        return rows;
    } catch (error) {
        return [];
    }
}

export default async function PagosPage() {
    const stats = await getStats();
    const recentCobros = await getRecentCobros();

    return (
        <div className="space-y-8">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Pagos y Cobros</h1>
                    <p className="text-muted-foreground mt-2">Control financiero, recibos y facturación del centro.</p>
                </div>
                <div className="flex space-x-3">
                    <button className="bg-secondary text-foreground px-4 py-2 rounded-lg font-medium hover:bg-border transition-colors">
                        Generar Remesa
                    </button>
                    <button className="flex items-center space-x-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg font-medium hover:opacity-90 transition-opacity">
                        <Plus className="h-5 w-5" />
                        <span>Nuevo Recibo</span>
                    </button>
                </div>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
                    <div className="flex items-center justify-between mb-4">
                        <div className="p-2 bg-emerald-500/10 rounded-lg">
                            <TrendingUp className="h-6 w-6 text-emerald-600" />
                        </div>
                        <span className="text-xs font-medium text-emerald-600 bg-emerald-500/10 px-2 py-1 rounded-full">+12% vs mes ant.</span>
                    </div>
                    <p className="text-sm font-medium text-muted-foreground">Total Recaudado</p>
                    <p className="text-3xl font-bold">€{stats.recaudado.toLocaleString()}</p>
                </div>

                <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
                    <div className="flex items-center justify-between mb-4">
                        <div className="p-2 bg-orange-500/10 rounded-lg">
                            <Clock className="h-6 w-6 text-orange-600" />
                        </div>
                    </div>
                    <p className="text-sm font-medium text-muted-foreground">Pendiente de Cobro</p>
                    <p className="text-3xl font-bold text-orange-600">€{stats.pendiente.toLocaleString()}</p>
                </div>

                <div className="rounded-xl border border-border bg-card p-6 shadow-sm relative overflow-hidden group">
                    <div className="absolute right-[-20px] top-[-20px] opacity-10 group-hover:scale-110 transition-transform">
                        <CreditCard className="h-32 w-32" />
                    </div>
                    <p className="text-sm font-medium text-muted-foreground mb-4">Acciones Rápidas</p>
                    <div className="space-y-2">
                        <button className="w-full text-left text-sm font-medium hover:text-primary transition-colors flex items-center">
                            <ArrowUpRight className="h-4 w-4 mr-2" /> Emitir Facturas Mensuales
                        </button>
                        <button className="w-full text-left text-sm font-medium hover:text-primary transition-colors flex items-center">
                            <ArrowUpRight className="h-4 w-4 mr-2" /> Revisar Devoluciones
                        </button>
                    </div>
                </div>
            </div>

            <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
                <div className="px-6 py-4 border-b border-border bg-muted/30 flex justify-between items-center">
                    <h3 className="font-semibold">Últimos Movimientos</h3>
                    <button className="text-sm text-primary font-medium hover:underline">Ver todo el historial</button>
                </div>
                <table className="w-full text-left border-collapse">
                    <thead className="bg-muted/50 border-b border-border">
                        <tr>
                            <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Alumno</th>
                            <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Concepto</th>
                            <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Fecha</th>
                            <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Importe</th>
                            <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Estado</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {recentCobros.map((cobro: any) => (
                            <tr key={cobro.id} className="hover:bg-muted/30 transition-colors">
                                <td className="px-6 py-4 font-medium">{cobro.nombre_completo}</td>
                                <td className="px-6 py-4 text-sm">{cobro.concepto}</td>
                                <td className="px-6 py-4 text-sm text-muted-foreground">
                                    {new Date(cobro.fecharecibo).toLocaleDateString()}
                                </td>
                                <td className="px-6 py-4 font-bold text-foreground">€{cobro.importefinal}</td>
                                <td className="px-6 py-4">
                                    <span className={`px-2 py-1 rounded-full text-xs font-semibold ${cobro.pagado ? 'bg-emerald-500/10 text-emerald-600' : 'bg-orange-500/10 text-orange-600'}`}>
                                        {cobro.pagado ? 'Pagado' : 'Pendiente'}
                                    </span>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}
