import React, { useMemo } from 'react';
import { motion } from 'framer-motion';
import { useOutletContext } from 'react-router-dom';
import { TrendingUp, CreditCard, AlertCircle, ArrowUpRight, DollarSign, Calendar } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, Legend } from 'recharts';

export const Revenues = () => {
  const { invoices, overageInvoices, clients } = useOutletContext<any>();

  const stats = useMemo(() => {
    let totalRecurring = 0;
    let totalOverage = 0;
    let unpaidCount = 0;

    invoices?.forEach((inv: any) => {
      if (inv.status === 'paid' || inv.status === 'Payée' || inv.status === 'Payé') {
        totalRecurring += parseFloat(inv.amount || '0');
      } else {
        unpaidCount++;
      }
    });

    overageInvoices?.forEach((oinv: any) => {
      if (oinv.status === 'paid' || oinv.status === 'Payée' || oinv.status === 'Payé') {
        totalOverage += parseFloat(oinv.amount || '0');
      } else {
        unpaidCount++;
      }
    });

    return { totalRecurring, totalOverage, totalRevenue: totalRecurring + totalOverage, unpaidCount };
  }, [invoices, overageInvoices]);

  const chartData = useMemo(() => {
    const data = [
      { name: 'Jan', recurring: 0, overage: 0 },
      { name: 'Fév', recurring: 0, overage: 0 },
      { name: 'Mar', recurring: 0, overage: 0 },
      { name: 'Avr', recurring: 0, overage: 0 },
      { name: 'Mai', recurring: 0, overage: 0 },
      { name: 'Juin', recurring: 0, overage: 0 },
      { name: 'Juil', recurring: 0, overage: 0 },
      { name: 'Août', recurring: 0, overage: 0 },
      { name: 'Sep', recurring: 0, overage: 0 },
      { name: 'Oct', recurring: 0, overage: 0 },
      { name: 'Nov', recurring: 0, overage: 0 },
      { name: 'Déc', recurring: 0, overage: 0 },
    ];

    invoices?.forEach((inv: any) => {
      if (inv.createdAt?.seconds && (inv.status === 'paid' || inv.status === 'Payée' || inv.status === 'Payé')) {
        const date = new Date(inv.createdAt.seconds * 1000);
        data[date.getMonth()].recurring += parseFloat(inv.amount || '0');
      }
    });

    overageInvoices?.forEach((oinv: any) => {
      if (oinv.createdAt?.seconds && (oinv.status === 'paid' || oinv.status === 'Payée' || oinv.status === 'Payé')) {
        const date = new Date(oinv.createdAt.seconds * 1000);
        data[date.getMonth()].overage += parseFloat(oinv.amount || '0');
      }
    });

    return data;
  }, [invoices, overageInvoices]);

  const topConsumers = useMemo(() => {
    const userMap: Record<string, { email: string, name: string, totalOverage: number, overageCount: number }> = {};
    
    overageInvoices?.forEach((oinv: any) => {
      if (oinv.status === 'paid' || oinv.status === 'Payée' || oinv.status === 'Payé') {
        const amount = parseFloat(oinv.amount || '0');
        if (!userMap[oinv.userId]) {
          const client = clients?.find((c: any) => c.email === oinv.userId);
          userMap[oinv.userId] = {
            email: oinv.userId,
            name: client ? `${client.firstName} ${client.lastName}` : oinv.userId,
            totalOverage: 0,
            overageCount: 0
          };
        }
        userMap[oinv.userId].totalOverage += amount;
        userMap[oinv.userId].overageCount += 1;
      }
    });

    return Object.values(userMap).sort((a, b) => b.totalOverage - a.totalOverage).slice(0, 5);
  }, [overageInvoices, clients]);

  return (
    <motion.div
      key="revenues"
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-8"
    >
      <div className="flex justify-between items-end mb-8">
        <div>
          <h2 className="text-3xl font-black text-slate-900 dark:text-white tracking-tight">Vue d'ensemble des revenus</h2>
          <p className="text-slate-500 dark:text-slate-400 mt-2 font-medium">Suivez la performance de vos abonnements et hors-forfaits</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-white dark:bg-slate-900 p-8 rounded-[2rem] border border-slate-100 dark:border-slate-800 shadow-sm relative overflow-hidden group">
          <div className="absolute top-0 right-0 p-8 opacity-10 group-hover:opacity-20 transition-opacity">
            <DollarSign className="w-24 h-24 text-blue-600" />
          </div>
          <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Revenu Total</p>
          <h3 className="text-4xl font-black text-slate-900 dark:text-white mb-2">{stats.totalRevenue.toLocaleString()} €</h3>
          <p className="text-sm font-bold text-green-500 flex items-center gap-1"><ArrowUpRight className="w-4 h-4" /> Global</p>
        </div>

        <div className="bg-white dark:bg-slate-900 p-8 rounded-[2rem] border border-slate-100 dark:border-slate-800 shadow-sm">
          <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Abonnements Récurrents</p>
          <h3 className="text-3xl font-black text-slate-900 dark:text-white mb-2">{stats.totalRecurring.toLocaleString()} €</h3>
          <p className="text-sm font-bold text-blue-500 flex items-center gap-1"><Calendar className="w-4 h-4" /> Base MRR</p>
        </div>

        <div className="bg-white dark:bg-slate-900 p-8 rounded-[2rem] border border-slate-100 dark:border-slate-800 shadow-sm bg-gradient-to-br from-white to-orange-50/30 dark:from-slate-900 dark:to-orange-900/10">
          <p className="text-xs font-bold text-orange-500 uppercase tracking-widest mb-2">Hors-Forfait (PAYG)</p>
          <h3 className="text-3xl font-black text-orange-600 dark:text-orange-400 mb-2">{stats.totalOverage.toLocaleString()} €</h3>
          <p className="text-sm font-bold text-orange-500/70 flex items-center gap-1"><TrendingUp className="w-4 h-4" /> {((stats.totalOverage / (stats.totalRevenue || 1)) * 100).toFixed(1)}% du revenu</p>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 bg-white dark:bg-slate-900 p-8 rounded-[3rem] border border-slate-100 dark:border-slate-800 shadow-sm">
          <div className="flex items-center justify-between mb-8">
            <h3 className="text-xl font-black text-slate-900 dark:text-white">Évolution des Revenus</h3>
          </div>
          <div className="h-[350px]">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e2e8f0" />
                <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 12, fontWeight: 600, fill: '#94a3b8' }} />
                <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 12, fontWeight: 600, fill: '#94a3b8' }} />
                <Tooltip 
                  cursor={{ fill: 'transparent' }}
                  contentStyle={{ borderRadius: '1rem', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
                />
                <Legend iconType="circle" wrapperStyle={{ paddingTop: '20px', fontSize: '12px', fontWeight: 'bold' }} />
                <Bar dataKey="recurring" name="Abonnements" stackId="a" fill="#2563eb" radius={[0, 0, 4, 4]} />
                <Bar dataKey="overage" name="Hors-Forfait" stackId="a" fill="#f97316" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="bg-white dark:bg-slate-900 p-8 rounded-[3rem] border border-slate-100 dark:border-slate-800 shadow-sm flex flex-col">
          <h3 className="text-xl font-black text-slate-900 dark:text-white mb-6">Top Consommateurs</h3>
          <p className="text-xs font-bold text-slate-400 mb-6 uppercase tracking-widest">Clients générant le plus de hors-forfait</p>
          
          <div className="flex-grow space-y-4">
            {topConsumers.length > 0 ? topConsumers.map((client, index) => (
              <div key={index} className="flex items-center justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-800/50 hover:bg-blue-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-blue-100 dark:hover:border-slate-700">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 font-bold text-sm">
                    {client.name.substring(0, 2).toUpperCase()}
                  </div>
                  <div>
                    <h4 className="text-sm font-bold text-slate-900 dark:text-white">{client.name}</h4>
                    <p className="text-xs font-medium text-slate-500">{client.overageCount} factures extra</p>
                  </div>
                </div>
                <div className="text-right">
                  <span className="text-base font-black text-orange-500">{client.totalOverage.toFixed(2)} €</span>
                </div>
              </div>
            )) : (
              <div className="flex flex-col items-center justify-center h-full text-center opacity-50">
                <AlertCircle className="w-12 h-12 text-slate-400 mb-4" />
                <p className="text-sm font-bold text-slate-500">Aucun hors-forfait enregistré pour le moment.</p>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-slate-900 rounded-[3rem] border border-slate-100 dark:border-slate-800 shadow-sm overflow-hidden">
        <div className="p-8 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center">
          <h3 className="text-xl font-black text-slate-900 dark:text-white">Dernières Factures de Hors-Forfait</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50 dark:bg-slate-800/50">
              <tr>
                <th className="px-8 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-widest">Période</th>
                <th className="px-8 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-widest">Client</th>
                <th className="px-8 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-widest">Dépassement</th>
                <th className="px-8 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-widest">Montant</th>
                <th className="px-8 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-widest">Statut</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
              {overageInvoices?.slice(0, 10).map((invoice: any) => {
                const isPaid = invoice.status === 'paid' || invoice.status === 'Payé' || invoice.status === 'Payée';
                return (
                  <tr key={invoice.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors">
                    <td className="px-8 py-5">
                      <span className="font-bold text-slate-900 dark:text-white">{invoice.period}</span>
                    </td>
                    <td className="px-8 py-5">
                      <span className="font-medium text-slate-600 dark:text-slate-300">{invoice.userId}</span>
                    </td>
                    <td className="px-8 py-5">
                      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-bold bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400">
                        {invoice.breakdown?.appointments?.excess || 0} RDV
                      </span>
                    </td>
                    <td className="px-8 py-5">
                      <span className="font-black text-slate-900 dark:text-white">{parseFloat(invoice.amount).toFixed(2)} €</span>
                    </td>
                    <td className="px-8 py-5">
                      <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold ${
                        isPaid ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' 
                        : 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'
                      }`}>
                        {isPaid ? 'Payé' : 'En attente'}
                      </span>
                    </td>
                  </tr>
                );
              })}
              {(!overageInvoices || overageInvoices.length === 0) && (
                <tr>
                  <td colSpan={5} className="px-8 py-12 text-center text-slate-500 font-medium">
                    Aucune facture de hors-forfait n'a été générée.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </motion.div>
  );
};
