/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglets Clients et Facturation
 * =========================================================================
 */

const { useState } = React;
const { 
    Users, KeyRound, ShieldAlert, Shield, Zap, MessageSquare, 
    Trash2, Loader, CheckCircle, Mail, AlertTriangle, FileText, 
    Download, RefreshCw 
} = window;

// =========================================================================
// 1. ONGLET : BASE CLIENTS
// =========================================================================

window.AdminClientsTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [accessRequestModal, setAccessRequestModal] = useState(null);
    const [creditModal, setCreditModal] = useState(null);
    const [pwdRequest, setPwdRequest] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);

    const clients = data.clients || [];

    const sendAccessRequest = async (uid, mode) => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/request_access', { 
                method: 'POST', 
                body: JSON.stringify({ uid, mode }) 
            });
            if ((await res.json()).status === 'success') {
                showToast("Demande d'accès envoyée avec succès.", "success");
                setAccessRequestModal(null);
                refreshData();
            } else {
                showToast("Erreur lors de la demande", "error");
            }
        } catch (e) {
            showToast("Erreur réseau", "error");
        } finally { setIsSaving(false); }
    };

    const revokeAccess = async (uid) => {
        setConfirmDialog({
            title: "Révocation d'accès",
            message: "Êtes-vous sûr de vouloir révoquer l'autorisation d'accès technique pour ce client ?",
            confirmText: "Oui, révoquer",
            isDestructive: true,
            onConfirm: async () => {
                setIsSaving(true);
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/revoke_access', { 
                        method: 'POST', 
                        body: JSON.stringify({ uid }) 
                    });
                    if ((await res.json()).status === 'success') {
                        showToast("Accès révoqué.", "success");
                        refreshData();
                    } else {
                        showToast("Erreur lors de la révocation", "error");
                    }
                } finally { setIsSaving(false); }
            }
        });
    };

    const impersonateClient = async (uid) => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/impersonate', { 
                method: 'POST', 
                body: JSON.stringify({ uid }) 
            });
            if ((await res.json()).status === 'success') {
                window.location.href = '?'; 
            } else {
                showToast("Erreur d'accès", "error");
            }
        } finally { setIsSaving(false); }
    };

    const deleteClient = (uid, clientName) => {
        setPwdRequest({
            title: `Suppression du compte : ${clientName}`,
            desc: (<span>ATTENTION : Saisissez le mot de passe administrateur pour détruire définitivement le compte de <strong className="text-red-600 font-black text-base">{clientName}</strong> et toutes ses données associées. Cette action est irréversible.</span>),
            onConfirm: async (pwd) => {
                setIsSaving(true);
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/admin_delete', { 
                        method: 'POST', 
                        body: JSON.stringify({ uid, pwd }) 
                    });
                    if ((await res.json()).status === 'success') { 
                        showToast("Client supprimé avec succès.", "success"); 
                        refreshData(); 
                    } else {
                        showToast("Erreur de suppression (Mot de passe incorrect ?)", 'error');
                    }
                } finally { setIsSaving(false); }
            }
        });
    };

    const handleAddCredit = async (e) => {
        e.preventDefault();
        const amount = parseFloat(e.target.amount.value);
        const reason = e.target.reason.value;
        if (amount <= 0) return showToast("Montant invalide", "error");
        
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'invoices/credit', {
                method: 'POST',
                body: JSON.stringify({ client_uid: creditModal.client_uid, amount, reason })
            });
            const d = await res.json();
            if (d.status === 'success') {
                showToast("Crédit ajouté avec succès !", "success");
                setCreditModal(null);
                refreshData();
            } else {
                showToast(d.message, 'error');
            }
        } catch (err) {
            showToast("Erreur réseau", "error");
        }
        setIsSaving(false);
    };

    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">Base clients</h1>
                    <p className="text-slate-500 font-medium">Gestion des comptes et prise de contrôle.</p>
                </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {clients.map(c => {
                    const isImpersonable = c.admin_access_until && new Date(String(c.admin_access_until || '').replace(' ', 'T')) > new Date();
                    const isSuspended = c.paymentStatus === 'suspended';
                    return (
                        <div key={c.id} className="bg-white rounded-3xl p-5 shadow-sm border border-slate-200 flex flex-col gap-4 transition hover:shadow-md hover:border-blue-200 group">
                            <div className="flex justify-between items-start">
                                <div className="flex gap-3 min-w-0">
                                    <div className="w-12 h-12 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
                                        <Users size={24} />
                                    </div>
                                    <div className="min-w-0">
                                        <p className="font-black text-base text-slate-800 truncate" title={c.name}>{c.name}</p>
                                        <p className="text-xs text-slate-500 truncate" title={c.email}>{c.email}</p>
                                        <div className="flex items-center gap-2 mt-1">
                                            <p className="text-[10px] text-slate-400 font-mono">ID : {c.id.substring(0,8)}</p>
                                            {c.wallet_balance !== 0 && (
                                                <span className={`px-1.5 py-0.5 rounded text-[9px] font-black tracking-widest uppercase ${c.wallet_balance > 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'}`}>
                                                    {c.wallet_balance > 0 ? `Solde: +${c.wallet_balance.toFixed(2)}€` : `Dette: ${c.wallet_balance.toFixed(2)}€`}
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div className="flex items-center gap-2">
                                <span className={`px-2 py-1 inline-flex items-center justify-center text-[10px] font-black uppercase tracking-wider rounded-lg ${isSuspended ? 'bg-red-100 text-red-700' : 'bg-emerald-100 text-emerald-700'}`}>
                                    {isSuspended ? 'Suspendu' : 'Actif'}
                                </span>
                                {c.discount > 0 && <span className="px-2 py-1 bg-purple-100 text-purple-700 text-[10px] font-black tracking-wider uppercase rounded-lg">Remise {c.discount}%</span>}
                            </div>
                            
                            <div className="flex gap-2 pt-4 border-t border-slate-100 mt-auto">
                                {isImpersonable ? (
                                    <div className="flex-1 flex gap-2">
                                        <button onClick={() => impersonateClient(c.id)} title="Prendre le contrôle du compte client" className="flex-1 py-2 bg-emerald-600 text-white rounded-xl text-xs font-bold hover:bg-emerald-700 transition flex justify-center items-center gap-2 shadow-sm"><KeyRound size={14}/> Contrôler</button>
                                        <button onClick={() => revokeAccess(c.id)} title="Révoquer l'accès" className="px-3 py-2 bg-orange-100 text-orange-600 rounded-xl text-xs font-bold hover:bg-orange-200 transition flex justify-center items-center"><ShieldAlert size={14}/></button>
                                    </div>
                                ) : (
                                    <button onClick={() => setAccessRequestModal(c.id)} title="Demander l'accès au compte" className="flex-1 py-2 bg-slate-100 text-slate-600 rounded-xl text-xs font-bold hover:bg-slate-200 transition flex justify-center items-center gap-2"><Shield size={14}/> Accès</button>
                                )}
                                
                                <button onClick={() => setCreditModal({ client_uid: c.id, clientName: c.name || c.email })} title="Ajouter un crédit (Bon d'achat)" className="px-4 py-2 bg-emerald-50 text-emerald-600 rounded-xl hover:bg-emerald-100 transition flex justify-center items-center"><Zap size={16}/></button>

                                <button onClick={() => {
                                    const u = new URL(window.location);
                                    u.searchParams.set('chat_id', 'SUPPORT_' + c.id);
                                    window.history.replaceState({}, '', u);
                                    setActiveTab('messages');
                                }} title="Ouvrir la messagerie avec ce client" className="px-4 py-2 bg-blue-50 text-blue-600 rounded-xl hover:bg-blue-100 transition flex justify-center items-center"><MessageSquare size={16}/></button>
                                <button onClick={() => deleteClient(c.id, c.name || c.email)} title="Supprimer définitivement ce compte" className="px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition flex justify-center items-center"><Trash2 size={16}/></button>
                            </div>
                        </div>
                    );
                })}
                {clients.length === 0 && (
                    <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <Users size={48} className="mx-auto text-slate-300 mb-4" />
                        <p className="text-slate-500 italic">Aucun client enregistré.</p>
                    </div>
                )}
            </div>

            {/* MODALES LOCALES */}
            {accessRequestModal && (
                <window.Modal title="Demande d'accès" onClose={() => setAccessRequestModal(null)} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-blue-50 p-4 rounded-xl border border-blue-100 text-blue-800 text-sm leading-relaxed">
                            Comment souhaitez-vous envoyer la demande d'autorisation d'accès temporaire (24h) à ce client ?
                        </div>
                        <div className="flex flex-col gap-3">
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'chat')} disabled={isSaving} className="w-full py-3 bg-white border border-slate-200 text-slate-700 font-bold rounded-xl hover:bg-slate-50 transition text-sm flex items-center justify-center gap-2 shadow-sm">
                                <MessageSquare size={16}/> Dans la messagerie (Recommandé)
                            </button>
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'email')} disabled={isSaving} className="w-full py-3 bg-white border border-slate-200 text-slate-700 font-bold rounded-xl hover:bg-slate-50 transition text-sm flex items-center justify-center gap-2 shadow-sm">
                                <Mail size={16}/> Par e-mail
                            </button>
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'both')} disabled={isSaving} className="w-full py-3 bg-emerald-600 text-white font-bold rounded-xl hover:bg-emerald-700 shadow-md transition text-sm flex items-center justify-center gap-2">
                                <CheckCircle size={16}/> Les deux
                            </button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {creditModal && (
                <window.Modal title={`Créditer le compte : ${creditModal.clientName}`} onClose={() => setCreditModal(null)} preventClose={isSaving}>
                    <form onSubmit={handleAddCredit} className="space-y-4">
                        <div className="bg-emerald-50 text-emerald-800 p-4 rounded-xl border border-emerald-100 text-sm">
                            <strong>Ajout d'un crédit (bon d'achat)</strong><br/>
                            Ce montant sera ajouté au solde du client et déduit automatiquement de ses prochains achats ou abonnements.
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Montant à créditer (€)</label>
                            <input type="number" step="0.01" min="0.01" name="amount" required className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500" placeholder="Ex: 50.00" />
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Motif (visible par le client)</label>
                            <input type="text" name="reason" required defaultValue="Geste commercial / Bon d'achat" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500" />
                        </div>
                        <div className="flex gap-3 pt-4">
                            <button type="button" onClick={() => setCreditModal(null)} className="flex-1 py-3 bg-slate-100 text-slate-700 font-bold rounded-xl hover:bg-slate-200">Annuler</button>
                            <button type="submit" disabled={isSaving} className="flex-1 py-3 bg-emerald-600 text-white font-black uppercase tracking-widest rounded-xl hover:bg-emerald-700 flex justify-center items-center gap-2">
                                {isSaving ? <Loader className="animate-spin" size={18}/> : <CheckCircle size={18}/>} Valider
                            </button>
                        </div>
                    </form>
                </window.Modal>
            )}

            {pwdRequest && (
                <window.Modal title={pwdRequest.title} onClose={() => setPwdRequest(null)} zIndex="z-[250]">
                    <div className="text-sm text-slate-600 mb-6 font-medium leading-relaxed">{pwdRequest.desc}</div>
                    <form onSubmit={(e) => {
                        e.preventDefault();
                        const pwd = e.target.pwd.value;
                        if(pwd) { pwdRequest.onConfirm(pwd); setPwdRequest(null); }
                    }}>
                        <input name="pwd" type="password" autoFocus required placeholder="Mot de passe administrateur..." className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition mb-4" />
                        <button type="submit" className="w-full bg-slate-900 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg">Confirmer l'action</button>
                    </form>
                </window.Modal>
            )}

            {confirmDialog && <window.ConfirmModal {...confirmDialog} zIndex="z-[250]" onCancel={() => setConfirmDialog(null)} />}
        </div>
    );
};


// =========================================================================
// 2. ONGLET : FACTURATION GLOBALE
// =========================================================================

window.AdminInvoicesTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [refundModal, setRefundModal] = useState(null);

    const clients = data.clients || [];

    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 > refundModal.invoice.amount) return showToast("Montant invalide", "error");
        
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'invoices/refund', {
                method: 'POST',
                body: JSON.stringify({ invoice_ref: refundModal.invoice.invoiceNumber, amount, mode, reason })
            });
            const d = await res.json();
            if (d.status === 'success') {
                showToast("Remboursement ou avoir traité avec succès !", "success");
                setRefundModal(null);
                refreshData();
            } else {
                showToast(d.message, 'error');
            }
        } catch (err) {
            showToast("Erreur réseau", "error");
        }
        setIsSaving(false);
    };

    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 les clients.</p>
                </div>
                <a href="?api=invoices/export_csv" className="bg-white border border-slate-200 text-slate-700 px-4 py-2.5 rounded-xl font-bold text-sm hover:bg-slate-50 transition shadow-sm flex items-center gap-2">
                    <Download size={16}/> Export CSV
                </a>
            </div>
            
            <div className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-x-auto">
                <table className="w-full text-left border-collapse whitespace-nowrap">
                    <thead>
                        <tr className="bg-slate-50 text-[10px] uppercase tracking-widest text-slate-500 border-b border-slate-200">
                            <th className="p-4 font-bold">Date</th>
                            <th className="p-4 font-bold">Client / Panneau</th>
                            <th className="p-4 font-bold">Détail</th>
                            <th className="p-4 font-bold">Montant</th>
                            <th className="p-4 font-bold text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                        {data.invoices?.map((inv, i) => {
                            const client = clients.find(c => c.id === inv.clientName);
                            return (
                                <tr key={i} className="hover:bg-slate-50 transition group">
                                    <td className="p-4 text-sm font-bold text-slate-700">
                                        {new Date(String(inv.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR')}
                                    </td>
                                    <td className="p-4">
                                        <div className="text-sm font-bold text-emerald-700 truncate max-w-[200px]" title={client?.name || 'Client Inconnu'}>
                                            {client?.name || 'Client Inconnu'}
                                        </div>
                                        <div className="text-xs text-slate-500 truncate max-w-[200px]" title={inv.panneauName}>
                                            {inv.panneauName}
                                        </div>
                                    </td>
                                    <td className="p-4 text-sm text-slate-600">{inv.type}</td>
                                    <td className="p-4 text-sm font-black text-slate-800">{inv.amount} €</td>
                                    <td className="p-4 text-right">
                                        <a href={`?api=invoices/download&ref=${inv.invoiceNumber}`} title="Télécharger la facture" className="inline-flex p-2 bg-slate-100 text-slate-600 rounded-lg hover:bg-slate-200 transition shadow-sm">
                                            <Download size={16}/>
                                        </a>
                                        {!inv.type.includes('Avoir') && (
                                            <button onClick={() => setRefundModal({ invoice: inv, clientName: client?.name || 'Client' })} title="Émettre un avoir / Rembourser" className="inline-flex p-2 ml-2 bg-orange-50 text-orange-600 rounded-lg hover:bg-orange-100 transition shadow-sm border border-orange-200">
                                                <RefreshCw size={16}/>
                                            </button>
                                        )}
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
                {(!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">
                        <FileText size={48} className="mx-auto text-slate-300 mb-4" />
                        <p className="text-slate-500 italic">Aucune facture émise.</p>
                    </div>
                )}
            </div>

            {/* MODALE DE REMBOURSEMENT */}
            {refundModal && (
                <window.Modal title={`Avoir / remboursement - Réf. ${refundModal.invoice.invoiceNumber}`} onClose={() => setRefundModal(null)} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={handleRefund} className="space-y-4">
                        <div className="bg-orange-50 text-orange-800 p-4 rounded-xl border border-orange-100 text-sm">
                            <strong>Facture initiale : {refundModal.invoice.amount} € ({refundModal.clientName})</strong><br/>
                            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 (€)</label>
                            <input type="number" step="0.01" min="0.01" max={refundModal.invoice.amount} defaultValue={refundModal.invoice.amount} 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</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 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)</label>
                            <input type="text" name="reason" required defaultValue="Remboursement / Annulation" 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">
                            <button type="button" onClick={() => setRefundModal(null)} className="flex-1 py-3 bg-slate-100 text-slate-700 font-bold rounded-xl hover:bg-slate-200">Annuler</button>
                            <button type="submit" disabled={isSaving} className="flex-1 py-3 bg-orange-600 text-white font-black uppercase tracking-widest rounded-xl hover:bg-orange-700 flex justify-center items-center gap-2">
                                {isSaving ? <Loader className="animate-spin" size={18}/> : <CheckCircle size={18}/>} Confirmer
                            </button>
                        </div>
                    </form>
                </window.Modal>
            )}
        </div>
    );
};

/*
		EOF	========== [_www/_react/_admin_clients_factures.jsx]
*/