/**
 * TaxiBook Partner - Factures View
 * =================================
 * Liste des factures (basées sur les courses terminées)
 * Groupées par mois avec total mensuel et téléchargement PDF
 */

const FacturesView = ({ bookings, setToast }) => {
    const [selectedMonth, setSelectedMonth] = useState('all');

    // Ne garder que les courses facturables (terminées)
    const completed = (bookings || []).filter(b => b.status === 'completed');

    // Grouper par mois (YYYY-MM)
    const byMonth = {};
    completed.forEach(b => {
        const d = new Date(b.completed_at || b.pickup_datetime);
        if (isNaN(d.getTime())) return;
        const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
        if (!byMonth[key]) {
            byMonth[key] = {
                key,
                label: d.toLocaleDateString('fr-CH', { month: 'long', year: 'numeric' }),
                bookings: [],
                total: 0
            };
        }
        byMonth[key].bookings.push(b);
        byMonth[key].total += parseFloat(b.price || 0);
    });

    const months = Object.values(byMonth).sort((a, b) => b.key.localeCompare(a.key));
    const visibleMonths = selectedMonth === 'all' ? months : months.filter(m => m.key === selectedMonth);

    const grandTotal = months.reduce((s, m) => s + m.total, 0);
    const grandCount = completed.length;

    const sourceLabels = {
        partner_app: 'Portail',
        manager: 'Manager',
        agent: 'Agent',
        smart: 'Smart',
        tablet: 'Tablet',
        ivr: 'IVR',
        minisite: 'Mini-site',
        site: 'Site',
        app_client: 'App Client',
        app_my: 'App MyTaxi'
    };

    const downloadInvoice = (booking) => {
        setToast({ message: 'Téléchargement PDF bientôt disponible', type: 'info' });
    };

    const downloadMonthly = (month) => {
        setToast({ message: `Facture mensuelle ${month.label} bientôt disponible`, type: 'info' });
    };

    return (
        <div className="animate-fade-in">
            <div className="flex items-center justify-between mb-6">
                <div>
                    <h2 className="text-2xl font-bold text-dark-900">Factures</h2>
                    <p className="text-dark-500">{grandCount} course(s) facturable(s) • {grandTotal.toFixed(2)} CHF au total</p>
                </div>
            </div>

            {/* Stats globales */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div className="bg-white rounded-2xl p-5 border-2 border-dark-200">
                    <p className="text-xs uppercase tracking-wider text-dark-500 mb-1">Total facturable</p>
                    <p className="text-2xl font-bold text-dark-900">{grandTotal.toFixed(2)} CHF</p>
                </div>
                <div className="bg-white rounded-2xl p-5 border-2 border-dark-200">
                    <p className="text-xs uppercase tracking-wider text-dark-500 mb-1">Nombre de courses</p>
                    <p className="text-2xl font-bold text-dark-900">{grandCount}</p>
                </div>
                <div className="bg-white rounded-2xl p-5 border-2 border-dark-200">
                    <p className="text-xs uppercase tracking-wider text-dark-500 mb-1">Mois facturés</p>
                    <p className="text-2xl font-bold text-dark-900">{months.length}</p>
                </div>
            </div>

            {/* Filtre mois */}
            {months.length > 0 && (
                <div className="flex gap-2 mb-6 flex-wrap">
                    <button
                        onClick={() => setSelectedMonth('all')}
                        className={`px-4 py-2 rounded-lg font-medium transition flex items-center gap-2 ${
                            selectedMonth === 'all'
                                ? 'bg-primary-500 text-white'
                                : 'bg-dark-100 text-dark-600 hover:bg-dark-200'
                        }`}
                    >
                        <i className="fas fa-list"></i>
                        Tous les mois
                    </button>
                    {months.map(m => (
                        <button
                            key={m.key}
                            onClick={() => setSelectedMonth(m.key)}
                            className={`px-4 py-2 rounded-lg font-medium transition flex items-center gap-2 capitalize ${
                                selectedMonth === m.key
                                    ? 'bg-primary-500 text-white'
                                    : 'bg-dark-100 text-dark-600 hover:bg-dark-200'
                            }`}
                        >
                            <i className="fas fa-calendar"></i>
                            {m.label}
                        </button>
                    ))}
                </div>
            )}

            {visibleMonths.length === 0 ? (
                <div className="bg-white rounded-2xl p-12 border-2 border-dark-200 text-center">
                    <div className="w-16 h-16 bg-dark-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i className="fas fa-file-invoice text-2xl text-dark-400"></i>
                    </div>
                    <h3 className="text-lg font-semibold text-dark-700 mb-2">Aucune facture</h3>
                    <p className="text-dark-500">Les factures apparaîtront dès qu'une course sera terminée</p>
                </div>
            ) : (
                <div className="space-y-6">
                    {visibleMonths.map(month => (
                        <div key={month.key} className="bg-white rounded-2xl border-2 border-dark-200 overflow-hidden">
                            <div className="px-6 py-4 bg-dark-50 border-b border-dark-200 flex items-center justify-between">
                                <div>
                                    <h3 className="text-lg font-bold text-dark-900 capitalize">{month.label}</h3>
                                    <p className="text-sm text-dark-500">{month.bookings.length} course(s) • {month.total.toFixed(2)} CHF</p>
                                </div>
                                <button
                                    onClick={() => downloadMonthly(month)}
                                    className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition flex items-center gap-2"
                                >
                                    <i className="fas fa-file-pdf"></i>
                                    Facture mensuelle
                                </button>
                            </div>
                            <div className="divide-y divide-dark-100">
                                {month.bookings.map(b => (
                                    <div key={b.id || b.uid} className="px-6 py-4 flex items-center justify-between hover:bg-dark-50 transition">
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2 flex-wrap mb-1">
                                                <span className="text-sm font-semibold text-dark-900">#{b.confirmation_code || b.uid?.slice(-8)}</span>
                                                <span className="text-xs text-dark-500">
                                                    {new Date(b.completed_at || b.pickup_datetime).toLocaleDateString('fr-CH', {
                                                        day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'
                                                    })}
                                                </span>
                                                {b.source && (
                                                    <span className="px-2 py-0.5 rounded text-xs font-medium bg-dark-100 text-dark-600">
                                                        {sourceLabels[b.source] || b.source}
                                                    </span>
                                                )}
                                            </div>
                                            <p className="text-sm text-dark-600 truncate">
                                                {b.pickup_address || b.package_name || '—'} → {b.destination_address || 'selon forfait'}
                                            </p>
                                            {(b.guest_name || b.driver_name) && (
                                                <p className="text-xs text-dark-500 mt-1">
                                                    {b.guest_name && <span><i className="fas fa-user mr-1"></i>{b.guest_name} </span>}
                                                    {b.driver_name && <span className="text-emerald-600 ml-2"><i className="fas fa-id-badge mr-1"></i>{b.driver_name}</span>}
                                                </p>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-3 ml-4">
                                            <p className="text-lg font-bold text-dark-900">{parseFloat(b.price || 0).toFixed(2)} CHF</p>
                                            <button
                                                onClick={() => downloadInvoice(b)}
                                                className="px-3 py-2 text-sm bg-dark-100 text-dark-700 rounded-lg hover:bg-dark-200 transition flex items-center gap-2"
                                                title="Télécharger la facture"
                                            >
                                                <i className="fas fa-file-pdf"></i>
                                                <span className="hidden md:inline">PDF</span>
                                            </button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};
