/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglet Facturation Globale
 * =========================================================================
 */

window.AdminInvoicesTab = ({ data, refreshData, showToast, setActiveTab, openLocalModal, openLocalDialog, closeCurrentLayer, activeModal, activeDialog, targetId }) => {
    const { useState } = React;
    
    // FACTORISATION : Utilisation du Hook global de gestion des modales par URL
    const { activeModal: urlModal, activeDialog: urlDialog, targetId: urlTargetId, openModal, openDialog, closeCurrentLayer: urlCloseLayer } = window.useUrlModal();
    
    // Priorité aux props passées par le parent, sinon fallback sur le hook
    const routerActiveModal = activeModal || urlModal;
    const routerActiveDialog = activeDialog || urlDialog;
    const routerCloseLayer = closeCurrentLayer || urlCloseLayer;
    const routerOpenModal = openLocalModal || openModal;
    const routerOpenDialog = openLocalDialog || openDialog;

    const [isSaving, setIsSaving] = useState(false);
    
    // Cibles des modales
    const [refundTarget, setRefundTarget] = useState(null);
    const [archives, setArchives] = useState([]);
    const [loadingArchives, setLoadingArchives] = useState(false);

    // FACTORISATION : Récupération sécurisée et propre des icônes
    const {
        DownloadIcon, RefreshCwIcon, FileTextIcon, LoaderIcon, 
        CheckCircleIcon, ArchiveIcon
    } = window.getIcons();

    const Modal = window.Modal || (() => null);
    const Button = window.Button || (({children}) => <button>{children}</button>);

    const clients = data.clients || [];
    const isImpersonating = data.settings?.impersonating === true;

    const handleRefund = async (e) => {
        e.preventDefault();
        const amount = parseFloat(e.target.amount.value);
        const reason = e.target.reason.value;
        const mode = e.target.mode.value;
        
        if (amount <= 0 || amount > refundTarget.maxRefundable) return showToast("Montant invalide", "error");
        
        const d = await window.apiFetch('invoices/refund', {
            body: { invoice_ref: refundTarget.invoice.invoiceNumber, amount, mode, reason },
            setLoading: setIsSaving,
            successMessage: "Remboursement ou avoir traité avec succès !"
        });

        if (d) {
            routerCloseLayer();
            refreshData();
        }
    };

    const openLegalArchives = async () => {
        routerOpenModal('legal_archive');
        const d = await window.apiFetch('invoices/legal_archive', { 
            method: 'GET', 
            setLoading: setLoadingArchives 
        });

        if (d) {
            setArchives(d.data || []);
        } else {
            routerCloseLayer();
        }
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Facturation globale</h1>
                    <p className="text-slate-500 font-medium">Historique des paiements de tous clients.</p>
                </div>
                <div className="flex gap-2">
                    {!isImpersonating && (
                        <Button variant="outline" icon={ArchiveIcon} onClick={openLegalArchives} className="py-2.5">
                            Archives légales
                        </Button>
                    )}
                    <Button variant="outline" icon={DownloadIcon} onClick={() => window.location.href = "?api=invoices/export_csv"} className="py-2.5">
                        Export CSV
                    </Button>
                </div>
            </div>
            
            <div className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden">
                <div className="flex flex-col">
                    {/* EN-TÊTES EN FLEXBOX */}
                    <div className="hidden md:flex items-center bg-slate-50 border-b border-slate-200 text-[10px] uppercase tracking-widest text-slate-500 font-bold shrink-0">
                        <div className="p-4 w-32 shrink-0">Date</div>
                        <div className="p-4 flex-1 min-w-0">Client / Panneau</div>
                        <div className="p-4 flex-1 min-w-0">Détail</div>
                        <div className="p-4 w-32 shrink-0">Montant</div>
                        <div className="p-4 w-32 shrink-0 text-right">Actions</div>
                    </div>
                    
                    {/* CONTENU EN FLEXBOX RESPONSIVE */}
                    <div className="divide-y divide-slate-100">
                        {data.invoices?.map((inv, i) => {
                            const client = clients.find(c => c.id === inv.clientName);
                            
                            const isAvoir = inv.type.includes('Avoir') || parseFloat(inv.amount) < 0;
                            let maxRefundable = 0;
                            
                            if (!isAvoir) {
                                const relatedAvoirs = data.invoices.filter(r => 
                                    (r.type.includes('Avoir') || parseFloat(r.amount) < 0) && 
                                    r.type.includes(inv.invoiceNumber)
                                );
                                const totalRefunded = relatedAvoirs.reduce((sum, r) => sum + Math.abs(parseFloat(r.amount)), 0);
                                maxRefundable = parseFloat((parseFloat(inv.amount) - totalRefunded).toFixed(2));
                            }

                            return (
                                <div key={i} className="flex flex-col md:flex-row md:items-center hover:bg-slate-50 transition w-full p-4 md:p-0 gap-2 md:gap-0">
                                    <div className="md:p-4 text-sm font-bold text-slate-700 md:w-32 shrink-0 flex items-center justify-between md:block">
                                        <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold">Date</span>
                                        <span>{window.formatDate ? window.formatDate(inv.created_at) : new Date(String(inv.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR')}</span>
                                    </div>
                                    <div className="md:p-4 flex-1 min-w-0 flex flex-col md:block">
                                        <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold mb-1">Client / Panneau</span>
                                        <div className="text-sm font-bold text-emerald-700 truncate" title={client?.name || 'Client inconnu'}>
                                            {client?.name || 'Client inconnu'}
                                        </div>
                                        <div className="text-xs text-slate-500 truncate" title={inv.panneauName}>
                                            {inv.panneauName}
                                        </div>
                                    </div>
                                    <div className="md:p-4 text-sm text-slate-600 flex-1 min-w-0 flex items-center justify-between md:block">
                                        <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold mr-2 shrink-0">Détail</span>
                                        <span className="truncate text-right md:text-left">{inv.type}</span>
                                    </div>
                                    <div className="md:p-4 text-sm font-black text-slate-800 md:w-32 shrink-0 flex items-center justify-between md:block">
                                        <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold">Montant</span>
                                        <span>{inv.amount} €</span>
                                    </div>
                                    <div className="md:p-4 md:w-32 shrink-0 flex justify-end gap-2 mt-2 md:mt-0 pt-3 md:pt-0 border-t border-slate-100 md:border-0">
                                        <Button variant="secondary" icon={DownloadIcon} onClick={() => window.location.href = `?api=invoices/download&ref=${inv.invoiceNumber}`} title="Télécharger la facture" className="p-2" />
                                        
                                        {!isAvoir && maxRefundable > 0 && (
                                            <Button 
                                                variant="warning" 
                                                icon={RefreshCwIcon} 
                                                onClick={() => { setRefundTarget({ invoice: inv, clientName: client?.name || 'Client', maxRefundable }); routerOpenDialog('refund'); }} 
                                                title={`Émettre un avoir (Max: ${maxRefundable}€)`} 
                                                className="p-2" 
                                            />
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
                {(!data.invoices || data.invoices.length === 0) && (
                    <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        {FileTextIcon && <FileTextIcon size={48} className="mx-auto text-slate-300 mb-4" />}
                        <p className="text-slate-500 italic">Aucune facture émise.</p>
                    </div>
                )}
            </div>

            {/* MODALES LOCALES DÉLÉGUÉES (LAYER 1 et 2) */}
            {routerActiveDialog === 'refund' && refundTarget && Modal && (
                <Modal title={`Avoir / remboursement - Réf. ${refundTarget.invoice.invoiceNumber}`} onClose={routerCloseLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={handleRefund} className="space-y-4">
                        <div className="text-xs text-slate-500 mb-2"><span className="text-red-500 font-black">*</span> Champs obligatoires</div>
                        <div className="bg-red-50 text-red-800 p-4 rounded-xl border border-red-100 text-sm mb-4">
                            <strong>Règle stricte :</strong> Aucun remboursement n'est jamais accepté sauf en cas d'erreur de facturation.
                        </div>
                        <div className="bg-orange-50 text-orange-800 p-4 rounded-xl border border-orange-100 text-sm">
                            <strong>Facture initiale : {refundTarget.invoice.amount} € ({refundTarget.clientName})</strong><br/>
                            
                            {parseFloat(refundTarget.invoice.amount) > refundTarget.maxRefundable && (
                                <span className="text-red-600 font-bold block mt-2 mb-2 p-2 bg-red-50 rounded-lg border border-red-200">
                                    Attention : Des avoirs partiels ont déjà été émis pour cette facture.<br/>
                                    Reste remboursable : {refundTarget.maxRefundable} €
                                </span>
                            )}
                            
                            Générez une facture d'avoir (partielle ou totale) pour annuler comptablement cette transaction.
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Montant de l'avoir (€) <span className="text-red-500">*</span></label>
                            <input type="number" step="0.01" min="0.01" max={refundTarget.maxRefundable} defaultValue={refundTarget.maxRefundable} name="amount" required className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-orange-500" />
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Méthode de restitution <span className="text-red-500">*</span></label>
                            <select name="mode" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-orange-500">
                                <option value="wallet">Crédit sur le site (avoir déduit des prochains achats)</option>
                                <option value="manual">Remboursement direct (manuel via le tableau de bord Stripe)</option>
                            </select>
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Motif de l'annulation (visible sur l'avoir) <span className="text-red-500">*</span></label>
                            <input type="text" name="reason" required defaultValue="Erreur de facturation" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-orange-500" />
                        </div>
                        <div className="flex gap-3 pt-4 border-t border-slate-100">
                            <Button variant="secondary" onClick={routerCloseLayer} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button type="submit" variant="primary" disabled={isSaving} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="flex-1 py-3 uppercase tracking-widest justify-center">
                                Confirmer
                            </Button>
                        </div>
                    </form>
                </Modal>
            )}

            {routerActiveModal === 'legal_archive' && Modal && (
                <Modal title="Coffre-fort des archives légales" onClose={routerCloseLayer} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-slate-50 border border-slate-200 p-4 rounded-xl text-sm text-slate-700 font-medium">
                            Cet espace inaltérable contient les copies des factures de tous les clients ayant été définitivement supprimés de la plateforme, pour garantir la conformité comptable.
                        </div>
                        
                        {loadingArchives ? (
                            <div className="py-12 text-center text-slate-500">
                                {LoaderIcon && <LoaderIcon size={32} className="animate-spin inline-block mb-4 text-slate-400"/>}
                                <p className="text-sm font-bold uppercase tracking-widest">Déchiffrement de l'index...</p>
                            </div>
                        ) : (
                            <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden flex flex-col">
                                <div className="hidden md:flex items-center bg-slate-50 border-b border-slate-200 text-[10px] uppercase tracking-widest text-slate-500 font-bold shrink-0">
                                    <div className="p-3 w-32 shrink-0">Réf / Date</div>
                                    <div className="p-3 flex-1 min-w-0">Client supprimé</div>
                                    <div className="p-3 w-28 shrink-0">Montant</div>
                                    <div className="p-3 w-20 shrink-0 text-right">PDF</div>
                                </div>
                                
                                <div className="divide-y divide-slate-100 max-h-[50vh] overflow-y-auto custom-scrollbar flex-1 min-h-0">
                                    {archives.map((arc, i) => (
                                        <div key={i} className="flex flex-col md:flex-row md:items-center hover:bg-slate-50 transition w-full p-3 gap-2 md:gap-0">
                                            <div className="md:p-3 md:w-32 shrink-0 flex items-center justify-between md:block">
                                                <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold">Réf / Date</span>
                                                <div className="text-right md:text-left">
                                                    <div className="text-xs font-bold text-slate-700">{arc.ref}</div>
                                                    <div className="text-[10px] text-slate-500">{window.formatDate ? window.formatDate(arc.date) : arc.date}</div>
                                                </div>
                                            </div>
                                            <div className="md:p-3 text-xs text-slate-600 flex-1 min-w-0 flex items-center justify-between md:block">
                                                <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold mr-2 shrink-0">Client supprimé</span>
                                                <span className="truncate text-right md:text-left" title={arc.clientName}>{arc.clientName}</span>
                                            </div>
                                            <div className="md:p-3 text-xs font-black text-slate-800 md:w-28 shrink-0 flex items-center justify-between md:block">
                                                <span className="md:hidden text-[10px] uppercase tracking-widest text-slate-400 font-bold">Montant</span>
                                                <span>{arc.amount} €</span>
                                            </div>
                                            <div className="md:p-3 md:w-20 shrink-0 flex justify-end mt-2 md:mt-0 pt-3 md:pt-0 border-t border-slate-100 md:border-0">
                                                <Button variant="outline" icon={DownloadIcon} onClick={() => window.location.href = `?api=invoices/legal_archive/download&ref=${arc.ref}`} title="Télécharger l'archive" className="p-2" />
                                            </div>
                                        </div>
                                    ))}
                                    {archives.length === 0 && (
                                        <div className="p-8 text-center text-slate-400 italic text-sm">
                                            Aucune archive légale trouvée.
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </Modal>
            )}
        </div>
    );
};

/* EOF ========== [_react/_admin_factures.jsx] */