/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglet Base Clients
 * =========================================================================
 */

window.AdminClientsTab = ({ 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 { activeDialog: urlDialog, openDialog, closeCurrentLayer: urlCloseLayer } = window.useUrlModal();
    
    // Priorité aux props passées par le parent, sinon fallback sur le hook
    const routerActiveDialog = activeDialog || urlDialog;
    const routerCloseLayer = closeCurrentLayer || urlCloseLayer;
    const routerOpenDialog = openLocalDialog || openDialog;

    const [isSaving, setIsSaving] = useState(false);
    
    // Cibles des modales
    const [accessTarget, setAccessTarget] = useState(null);
    const [creditTarget, setCreditTarget] = useState(null);
    const [editClientTarget, setEditClientTarget] = useState(null);
    const [pwdRequestData, setPwdRequestData] = useState(null);
    const [confirmConfig, setConfirmConfig] = useState(null);

    // FACTORISATION : Récupération sécurisée et propre des icônes
    const {
        UsersIcon, KeyRoundIcon, ShieldAlertIcon, ShieldIcon,
        ZapIcon, MessageSquareIcon, Trash2Icon, EditIcon,
        MailIcon, CheckCircleIcon, LoaderIcon
    } = window.getIcons();
    
    const Modal = window.Modal || (() => null);
    const ConfirmModal = window.ConfirmModal || (() => null);
    const PasswordPromptModal = window.PasswordPromptModal || (() => null);
    const Button = window.Button || (({children}) => <button>{children}</button>);
    const IconBadge = window.IconBadge || (() => null);

    const clients = data.clients || [];

    const sendAccessRequest = async (uid, mode) => {
        const d = await window.apiFetch('clients/request_access', { 
            body: { uid, mode },
            setLoading: setIsSaving,
            successMessage: "Demande d'accès envoyée avec succès."
        });
        if (d) {
            routerCloseLayer();
            refreshData();
        }
    };

    const revokeAccess = async (uid) => {
        setConfirmConfig({
            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 () => {
                routerCloseLayer();
                const d = await window.apiFetch('clients/revoke_access', { 
                    body: { uid },
                    setLoading: setIsSaving,
                    successMessage: "Accès révoqué."
                });
                if (d) refreshData();
            }
        });
        routerOpenDialog('confirm');
    };

    const impersonateClient = async (uid) => {
        const d = await window.apiFetch('auth/impersonate', { 
            body: { uid },
            setLoading: setIsSaving
        });
        if (d) window.location.href = '?'; 
    };

    const deleteClient = (uid, clientName) => {
        setPwdRequestData({
            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) => {
                const d = await window.apiFetch('clients/admin_delete', { 
                    body: { uid, pwd },
                    setLoading: setIsSaving,
                    successMessage: "Client supprimé avec succès."
                });
                if (d) {
                    routerCloseLayer();
                    refreshData(); 
                }
            }
        });
        routerOpenDialog('pwd_request');
    };

    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");
        
        const d = await window.apiFetch('invoices/credit', {
            body: { client_uid: creditTarget.client_uid, amount, reason },
            setLoading: setIsSaving,
            successMessage: "Crédit ajouté avec succès !"
        });

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

    const handleEditClientSubmit = async (e) => {
        e.preventDefault();
        const discount = parseInt(e.target.discount.value) || 0;
        const discountDuration = e.target.discountDuration.value;
        const paymentStatus = e.target.paymentStatus.value;
        
        const d = await window.apiFetch('clients/update', {
            body: {
                uid: editClientTarget.id,
                discount,
                discountDuration,
                paymentStatus
            },
            setLoading: setIsSaving,
            successMessage: "Client mis à jour avec succès."
        });

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

    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';
                    
                    // Calcul des statistiques du client
                    const twelveMonthsAgo = new Date();
                    twelveMonthsAgo.setMonth(twelveMonthsAgo.getMonth() - 12);
                    
                    const clientInvoices = (data.invoices || []).filter(inv => inv.clientName === c.id);
                    
                    // On laisse passer les avoirs pour qu'ils soient déduits comptablement
                    const revenue12m = clientInvoices
                        .filter(inv => {
                            const date = new Date(String(inv.created_at || '').replace(' ', 'T'));
                            return date >= twelveMonthsAgo;
                        })
                        .reduce((sum, inv) => sum + parseFloat(inv.amount || 0), 0);
                        
                    const clientPanels = (data.panneaux || []).filter(p => p.clientName === c.id);
                    const activePanelsCount = clientPanels.filter(p => p.status === 'Actif').length;
                    const draftPanelsCount = clientPanels.filter(p => p.status === 'Brouillon').length;

                    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 w-full">
                                    <IconBadge icon={UsersIcon} variant="info" size="lg" />
                                    <div className="min-w-0 flex-1">
                                        <p className="font-black text-base text-slate-800 truncate" title={c.name}>{c.name}</p>
                                        {c.full_name && <p className="text-xs font-bold text-slate-600 truncate" title={c.full_name}>{c.full_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>

                            {/* Statistiques Client */}
                            <div className="grid grid-cols-3 gap-2 mt-1 bg-slate-50 p-2 rounded-xl border border-slate-100 text-center">
                                <div>
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Revenu (12m)</p>
                                    <p className="font-black text-slate-700 text-xs">{revenue12m.toFixed(2)} €</p>
                                </div>
                                <div className="border-l border-slate-200">
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Actifs</p>
                                    <p className="font-black text-slate-700 text-xs">{activePanelsCount}</p>
                                </div>
                                <div className="border-l border-slate-200">
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Brouillons</p>
                                    <p className="font-black text-slate-700 text-xs">{draftPanelsCount}</p>
                                </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 ? 'Impayé (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 flex-wrap">
                                {isImpersonable ? (
                                    <div className="flex-1 flex gap-2">
                                        <Button variant="primary" icon={KeyRoundIcon} onClick={() => impersonateClient(c.id)} title="Prendre le contrôle du compte client" className="flex-1 justify-center">Contrôler</Button>
                                        <Button variant="warning" icon={ShieldAlertIcon} onClick={() => revokeAccess(c.id)} title="Révoquer l'accès" className="px-3" />
                                    </div>
                                ) : (
                                    <Button variant="secondary" icon={ShieldIcon} onClick={() => { setAccessTarget(c.id); routerOpenDialog('access_request'); }} title="Demander l'accès au compte" className="flex-1 justify-center">Accès</Button>
                                )}
                                
                                <Button variant="secondary" icon={EditIcon} onClick={() => { setEditClientTarget(c); routerOpenDialog('edit_client'); }} title="Modifier le statut ou la remise" className="px-3" />
                                <Button variant="success" icon={ZapIcon} onClick={() => { setCreditTarget({ client_uid: c.id, clientName: c.name || c.email }); routerOpenDialog('credit'); }} title="Ajuster le solde (Crédit / Dette)" className="px-3" />
                                <Button variant="info" icon={MessageSquareIcon} 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-3" />
                                <Button variant="danger" icon={Trash2Icon} onClick={() => deleteClient(c.id, c.name || c.email)} title="Supprimer définitivement ce compte" className="px-3" />
                            </div>
                        </div>
                    );
                })}
                {clients.length === 0 && (
                    <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <UsersIcon size={48} className="mx-auto text-slate-300 mb-4" />
                        <p className="text-slate-500 italic">Aucun client enregistré.</p>
                    </div>
                )}
            </div>

            {/* MODALES LOCALES DÉLÉGUÉES (LAYER 2) */}
            {routerActiveDialog === 'access_request' && accessTarget && Modal && (
                <Modal title="Demande d'accès" onClose={routerCloseLayer} 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 variant="outline" icon={MessageSquareIcon} onClick={() => sendAccessRequest(accessTarget, 'chat')} disabled={isSaving} className="w-full py-3 justify-center">
                                Dans la messagerie (recommandé)
                            </Button>
                            <Button variant="outline" icon={MailIcon} onClick={() => sendAccessRequest(accessTarget, 'email')} disabled={isSaving} className="w-full py-3 justify-center">
                                Par e-mail
                            </Button>
                            <Button variant="primary" icon={CheckCircleIcon} onClick={() => sendAccessRequest(accessTarget, 'both')} disabled={isSaving} className="w-full py-3 shadow-md justify-center">
                                Les deux
                            </Button>
                        </div>
                    </div>
                </Modal>
            )}

            {routerActiveDialog === 'credit' && creditTarget && Modal && (
                <Modal title={`Ajuster le solde : ${creditTarget.clientName}`} onClose={routerCloseLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={handleAddCredit} 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-emerald-50 text-emerald-800 p-4 rounded-xl border border-emerald-100 text-sm">
                            <strong>Ajout d'un crédit / Annulation de dette</strong><br/>
                            Ce montant sera ajouté au solde du client. S'il a une dette (solde négatif ou statut impayé), cela permettra de l'annuler en tout ou partie.
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Montant à créditer (€) <span className="text-red-500">*</span></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) <span className="text-red-500">*</span></label>
                            <input type="text" name="reason" required defaultValue="Geste commercial / Annulation de dette" 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 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">
                                Valider
                            </Button>
                        </div>
                    </form>
                </Modal>
            )}

            {routerActiveDialog === 'edit_client' && editClientTarget && Modal && (
                <Modal title={`Modifier le client : ${editClientTarget.name || editClientTarget.email}`} onClose={routerCloseLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={handleEditClientSubmit} 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>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Statut des paiements</label>
                            <select name="paymentStatus" defaultValue={editClientTarget.paymentStatus || 'ok'} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500">
                                <option value="ok">En règle (Actif)</option>
                                <option value="suspended">Impayé (Suspendu)</option>
                            </select>
                            <p className="text-[10px] text-slate-500 mt-1">Vous pouvez forcer manuellement le statut pour contourner un blocage Stripe.</p>
                        </div>

                        <div className="pt-2 border-t border-slate-100">
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Remise commerciale (%)</label>
                            <input type="number" min="0" max="100" name="discount" defaultValue={editClientTarget.discount || 0} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500" />
                        </div>

                        <div>
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Durée de validité de la remise <span className="text-red-500">*</span></label>
                            <select name="discountDuration" defaultValue={editClientTarget.discount_duration || '1'} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500">
                                <option value="1">1 mois</option>
                                <option value="2">2 mois</option>
                                <option value="3">3 mois</option>
                                <option value="6">6 mois</option>
                                <option value="9">9 mois</option>
                                <option value="12">12 mois</option>
                            </select>
                        </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">
                                Enregistrer
                            </Button>
                        </div>
                    </form>
                </Modal>
            )}

            {routerActiveDialog === 'pwd_request' && pwdRequestData && PasswordPromptModal && (
                <PasswordPromptModal
                    title={pwdRequestData.title}
                    desc={pwdRequestData.desc}
                    onConfirm={pwdRequestData.onConfirm}
                    onCancel={routerCloseLayer}
                    isSaving={isSaving}
                />
            )}

            {routerActiveDialog === 'confirm' && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} zIndex="z-[350]" onCancel={routerCloseLayer} />}
        </div>
    );
};

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