/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Client - Onglet : Factures et Avoirs
 * =========================================================================
 */

window.pano_ClientInvoicesTab = ({ data, myClientData, setPromptDialog, refreshData, setActiveTab, openLocalDialog }) => {
    const { useState } = React;
    const [isSaving, setIsSaving] = useState(false);

    const { DownloadIcon, ZapIcon, FileTextIcon, AlertTriangleIcon } = window.pano_getIcons();
    
    const Button = window.pano_Button || (() => null);
    const IconBadge = window.pano_IconBadge || (() => null);

    const handleRefundRequest = (inv) => {
        if (!setPromptDialog) return;
        
        setPromptDialog({
            title: "Demande d'analyse ou signalement",
            type: "info",
            message: `Veuillez indiquer le motif de votre demande concernant la facture ${inv.invoiceNumber} d'un montant de ${inv.amount} €. Aucun remboursement n'est jamais accepté sauf après demande explicite et validation stricte par l'administrateur (ex: erreur de facturation prouvée). Un ticket sera ouvert auprès de notre service comptabilité.`,
            placeholder: "Motif de votre demande...",
            confirmText: "Envoyer la demande",
            onConfirm: async (reason) => {
                const payload = {
                    panneauId: `SUPPORT_${myClientData.id}`,
                    detail: `Demande d'analyse concernant la facture ${inv.invoiceNumber} (${inv.amount} €).\nMotif : ${reason}`,
                    author: 'Client',
                    targetEmail: 'Admin',
                    type: 'billing'
                };
                
                const d = await window.pano_apiFetch('interactions', {
                    body: payload,
                    setLoading: setIsSaving,
                    successMessage: "Demande transmise au service comptabilité."
                });

                if (d) {
                    const u = new URL(window.location);
                    u.searchParams.set('chat_id', `SUPPORT_${myClientData.id}`);
                    window.history.pushState({ chat_id: `SUPPORT_${myClientData.id}` }, '', u);
                    window.dispatchEvent(new Event('popstate'));
                    if (refreshData) refreshData();
                }
            }
        });
        if (openLocalDialog) openLocalDialog('prompt');
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Factures</h1>
                    <p className="text-slate-500 font-medium">Historique comptable et paiements des achats sur <a href="https://eco-panneau.fr" className="text-emerald-600 hover:underline font-bold" target="_blank" rel="noopener noreferrer">eco-panneau.fr</a>.</p>
                </div>
                <Button variant="outline" icon={DownloadIcon} className="px-4 py-2 rounded-xl" onClick={() => window.location.href = window.pano_CONFIG.apiBaseUrl + "invoices/export_csv"}>
                    <span className="hidden sm:inline">Exporter en CSV</span>
                </Button>
            </div>

            {myClientData.wallet_balance > 0 && (
                <div className="bg-emerald-50 border border-emerald-200 p-5 rounded-3xl mb-6 flex flex-col sm:flex-row items-start sm:items-center justify-between shadow-sm gap-4">
                    <div className="flex items-center gap-4">
                        {IconBadge && <IconBadge icon={ZapIcon} variant="success" size="lg" className="shrink-0" />}
                        <div>
                            <p className="text-sm font-bold text-emerald-900">Solde disponible (Avoir / Crédit)</p>
                            <p className="text-xs text-emerald-700 mt-1 font-medium">Ce montant sera automatiquement déduit de vos prochaines commandes ou de vos factures d'abonnement.</p>
                        </div>
                    </div>
                    <div className="text-3xl font-black text-emerald-600 shrink-0">
                        {myClientData.wallet_balance.toFixed(2)} €
                    </div>
                </div>
            )}
            
            <div className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden">
                <div className="grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))] gap-4 p-4">
                    {(data.invoices || []).map((inv, i) => (
                        <div key={i} className="bg-slate-50 border border-slate-100 rounded-2xl p-4 flex flex-col gap-3 transition hover:shadow-sm">
                            <div className="flex justify-between items-start">
                                <div>
                                    <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Date</span>
                                    <span className="text-sm font-bold text-slate-700">{window.pano_formatDate ? window.pano_formatDate(inv.created_at) : new Date(String(inv.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR')}</span>
                                </div>
                                <div className="text-right">
                                    <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Montant</span>
                                    <span className="text-sm font-black text-slate-800">{inv.amount} €</span>
                                </div>
                            </div>
                            
                            <div className="pt-2 border-t border-slate-200">
                                <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Panneau</span>
                                <span className="text-sm text-slate-600 truncate block" title={inv.panneauName}>{inv.panneauName}</span>
                            </div>
                            
                            <div className="pt-2 border-t border-slate-200">
                                <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Détail</span>
                                <span className="text-sm text-slate-600 truncate block">{inv.type}</span>
                            </div>
                            
                            <div className="flex justify-end gap-2 pt-3 mt-auto border-t border-slate-200">
                                <Button variant="info" shape="square" icon={AlertTriangleIcon} onClick={() => handleRefundRequest(inv)} disabled={isSaving} title="Demande d'analyse ou signalement" className="p-2 shadow-none" />
                                <Button variant="secondary" shape="square" icon={DownloadIcon} onClick={() => window.location.href = `${window.pano_CONFIG.apiBaseUrl}invoices/download&ref=${inv.invoiceNumber}`} title="Télécharger la facture" className="p-2 shadow-none" />
                            </div>
                        </div>
                    ))}
                </div>
                {(!data.invoices || data.invoices.length === 0) && (
                    <div className="p-12 text-center text-slate-500 border-t border-slate-200">
                        <FileTextIcon size={48} className="mx-auto mb-4 opacity-50"/>
                        <p className="font-medium">Aucune facture pour le moment.</p>
                    </div>
                )}
            </div>
        </div>
    );
};

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