/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Admin - Onglet : Logistique (A1)
 * =========================================================================
 */

window.pano_AdminLogisticsTab = ({ data, refreshData, showToast, activeModal, activeDialog, targetId, openLocalModal, openLocalDialog, closeCurrentLayer }) => {
    const { useState, useEffect } = React;
    
    const routerActiveDialog = activeDialog || new URLSearchParams(window.location.search).get('dialog');
    const routerCloseLayer = closeCurrentLayer || (() => window.history.back());
    const routerOpenDialog = openLocalDialog || ((type) => {
        const u = new URL(window.location);
        u.searchParams.set('dialog', type);
        window.history.pushState({ dialog: type }, '', u);
        window.dispatchEvent(new Event('popstate'));
    });

    const [forceRender, setForceRender] = useState(0);
    useEffect(() => {
        if (!activeDialog) {
            const onPop = () => setForceRender(prev => prev + 1);
            window.addEventListener('popstate', onPop);
            return () => window.removeEventListener('popstate', onPop);
        }
    }, [activeDialog]);

    const [isSaving, setIsSaving] = useState(false);
    
    const [confirmConfig, setConfirmConfig] = useState(null);
    const [shippingTarget, setShippingTarget] = useState(null);
    const [trackingData, setTrackingData] = useState({ number: '', link: '' });
    
    const Button = window.pano_Button || (() => null);
    const ConfirmModal = window.pano_ConfirmModal || (() => null);
    const StatusBadge = window.pano_StatusBadge || (() => null);
    const Modal = window.pano_Modal || (() => null);

    const PackageIcon = window.pano_PackageIcon || (() => null);
    const CheckCircleIcon = window.pano_CheckCircleIcon || (() => null);
    const EyeIcon = window.pano_EyeIcon || (() => null);
    const UploadIcon = window.pano_UploadIcon || (() => null);
    const Trash2Icon = window.pano_Trash2Icon || (() => null);
    const EditIcon = window.pano_EditIcon || (() => null);
    const DownloadIcon = window.pano_DownloadIcon || (() => null);

    const handleA1Upload = async (c, e) => {
        const file = e.target.files[0];
        if(!file) return;
        const id = await window.pano_uploadFile(file, 'pdf', null, false, false, c.clientName, c.id);
        if (id) {
            const d = await window.pano_apiFetch('panneaux', {
                body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, a1PdfId: id }, a1PdfId: id },
                setLoading: setIsSaving, 
                successMessage: "Maquette A1 attachée avec succès !"
            });
            if(d) refreshData();
        }
        e.target.value = null;
    };

    const handleA1Delete = (c) => {
        setConfirmConfig({
            title: "Retirer la maquette", 
            message: "Voulez-vous retirer le fichier PDF A1 de ce panneau ?", 
            confirmText: "Retirer", 
            isDestructive: true,
            onConfirm: async () => {
                routerCloseLayer();
                const d = await window.pano_apiFetch('panneaux', {
                    body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, a1PdfId: '' }, a1PdfId: '' },
                    setLoading: setIsSaving, 
                    successMessage: "Maquette retirée."
                });
                if(d) refreshData();
            }
        });
        routerOpenDialog('confirm');
    };

    const updateShippingStatus = async (id, newStatus) => {
        const d = await window.pano_apiFetch('panneaux/shipping', {
            body: { id, shipping_status: newStatus },
            setLoading: setIsSaving,
            successMessage: "Statut logistique mis à jour."
        });
        if (d) refreshData();
    };

    const panneaux = data.panneaux || [];
    const clients = data.clients || [];
    const logisticPanels = panneaux.filter(p => p.physicalPanels > 0 && p.status === 'Actif');

    return (
        <div className="space-y-8 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">Logistique</h1>
                    <p className="text-slate-500 font-medium">Gestion des commandes de panneaux physiques sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="inline-block hover:opacity-80 transition ml-1"><window.pano_TextLogo className="text-sm text-emerald-600 hover:underline font-bold" /></a>.</p>
                </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(320px,1fr))] gap-4 p-4">
                    {logisticPanels.map((c, i) => {
                        const owner = clients.find(cl => cl.id === c.clientName);
                        return (
                            <div key={i} className="bg-slate-50 border border-slate-100 rounded-2xl p-5 flex flex-col gap-4 transition hover:shadow-md">
                                <div className="flex justify-between items-start gap-4">
                                    <div className="min-w-0 flex-1">
                                        <p className="font-black text-slate-800 text-lg truncate">{c.name}</p>
                                        <p className="text-sm font-bold text-emerald-700 truncate">{owner ? owner.name : c.clientName}</p>
                                        <p className="text-xs text-slate-500 mt-1 flex items-start gap-1"><PackageIcon size={14} className="shrink-0 mt-0.5"/> <span className="line-clamp-2">{c.shippingAddress || c.location}</span></p>
                                    </div>
                                    <div className="shrink-0 text-center bg-white p-2 rounded-xl border border-slate-200 shadow-sm min-w-[70px]">
                                        <span className="text-2xl font-black text-slate-800 leading-none">{c.physicalPanels}</span>
                                        <span className="block text-[9px] uppercase tracking-widest text-slate-400 font-bold mt-1">Qté</span>
                                    </div>
                                </div>
                                
                                <div className="pt-3 border-t border-slate-200 flex items-center justify-between">
                                    <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold">Statut logistique</span>
                                    <StatusBadge status={c.shipping_status || 'En attente'} />
                                </div>
                                
                                <div className="pt-3 border-t border-slate-200">
                                    <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-2">Maquette A1 pour impression</span>
                                    
                                    {c.a1PdfId ? (
                                        <div className="flex gap-2">
                                            <Button variant="secondary" onClick={() => window.open(`${window.pano_CONFIG.apiBaseUrl}file/download&type=pdf&id=${c.a1PdfId}`, '_blank')} className="flex-1 py-2 text-xs justify-center" icon={EyeIcon} title="Voir">Voir</Button>
                                            <Button variant="danger" shape="square" icon={Trash2Icon} onClick={() => handleA1Delete(c)} disabled={isSaving} className="p-2 shadow-none" title="Retirer" />
                                            {c.shipping_status === 'Validation en cours' && (
                                                <Button variant="success" icon={CheckCircleIcon} onClick={() => updateShippingStatus(c.id, "Attente d'impression")} disabled={isSaving} className="flex-1 py-2 text-xs justify-center">Valider</Button>
                                            )}
                                        </div>
                                    ) : (
                                        <div className="flex flex-col gap-2">
                                            <div className="flex gap-2">
                                                <Button variant="secondary" icon={DownloadIcon} onClick={async () => {
                                                    const blob = await window.pano_generateA1PDF(c);
                                                    const link = document.createElement('a'); 
                                                    link.href = URL.createObjectURL(blob); 
                                                    link.download = `Panneau_A1_${c.id}.pdf`; 
                                                    link.click();
                                                }} disabled={isSaving} className="py-2 text-xs flex-1 justify-center">
                                                    Contrôler
                                                </Button>
                                                <Button variant="success" icon={CheckCircleIcon} onClick={() => {
                                                    setConfirmConfig({
                                                        title: "Validation de la maquette", message: "Valider ce PDF généré automatiquement ?", confirmText: "Valider",
                                                        onConfirm: async () => {
                                                            const blob = await window.pano_generateA1PDF(c);
                                                            const file = new File([blob], `A1_${c.id}.pdf`, { type: 'application/pdf' });
                                                            const id = await window.pano_uploadFile(file, 'pdf', null, false, false, c.clientName, c.id);
                                                            await window.pano_apiFetch('panneaux', { body: { ...c, details: { ...c, a1PdfId: id }, a1PdfId: id }, setLoading: setIsSaving, successMessage: "Validé !" });
                                                            refreshData(); 
                                                            routerCloseLayer();
                                                        }
                                                    });
                                                    routerOpenDialog('confirm');
                                                }} disabled={isSaving} className="py-2 text-xs flex-1 justify-center">
                                                    Valider
                                                </Button>
                                            </div>
                                            <label className="flex items-center justify-center gap-2 bg-white border border-slate-200 text-slate-700 hover:bg-slate-100 hover:border-slate-300 py-2 rounded-xl text-xs font-bold cursor-pointer transition shadow-sm">
                                                <UploadIcon size={14} className="shrink-0"/> Attacher un fichier manuellement
                                                <input type="file" accept="application/pdf" className="hidden" onChange={(e) => handleA1Upload(c, e)} disabled={isSaving} />
                                            </label>
                                        </div>
                                    )}
                                </div>

                                <div className="pt-3 border-t border-slate-200 mt-auto">
                                    <Button variant="primary" onClick={() => { setShippingTarget(c); setTrackingData({number: c.tracking_number || '', link: c.tracking_link || ''}); routerOpenDialog('shipping'); }} disabled={isSaving || c.shipping_status === 'Expédié' || c.shipping_status === 'Livré' || !c.a1PdfId} className="w-full py-2.5 text-sm justify-center uppercase tracking-widest">
                                        Expédier la commande
                                    </Button>
                                    
                                    {c.shipping_status === 'Expédié' && (
                                        <div className="text-center bg-white p-3 rounded-xl border border-slate-200 mt-3 shadow-inner">
                                            <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">En acheminement</p>
                                            <p className="text-sm font-mono text-blue-600 font-bold select-all">{c.tracking_number}</p>
                                            <Button variant="ghost" icon={EditIcon} onClick={() => { setShippingTarget(c); setTrackingData({number: c.tracking_number || '', link: c.tracking_link || ''}); routerOpenDialog('shipping'); }} className="mt-2 w-full text-xs py-1.5 justify-center text-slate-500 hover:text-slate-800 bg-slate-50 hover:bg-slate-100">
                                                Modifier le suivi
                                            </Button>
                                        </div>
                                    )}
                                </div>
                            </div>
                        );
                    })}
                </div>
                {logisticPanels.length === 0 && (
                    <div className="p-12 text-center text-slate-500 border-t border-slate-200">
                        <PackageIcon size={48} className="mx-auto mb-4 opacity-50" />
                        <p className="font-medium">Aucune commande de panneau physique en cours.</p>
                    </div>
                )}
            </div>
            
            {routerActiveDialog === 'shipping' && shippingTarget && Modal && (
                <Modal title={shippingTarget.shipping_status === 'Expédié' ? "Mise à jour du suivi" : "Expédition de la commande"} onClose={routerCloseLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={async (e) => {
                        e.preventDefault();
                        const d = await window.pano_apiFetch('panneaux/shipping', { 
                            body: { id: shippingTarget.id, shipping_status: 'Expédié', tracking_number: trackingData.number, tracking_link: trackingData.link }, 
                            setLoading: setIsSaving, 
                            successMessage: "Suivi logistique mis à jour avec succès !" 
                        });
                        if(d) { refreshData(); routerCloseLayer(); }
                    }} className="space-y-4">
                        <div className="space-y-2">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Numéro de suivi du transporteur <span className="text-red-500">*</span></label>
                            <input type="text" required value={trackingData.number} onChange={e => setTrackingData({...trackingData, number: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" placeholder="Ex: 8J009088..." />
                        </div>
                        <div className="space-y-2">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Lien web du suivi (facultatif)</label>
                            <input type="url" value={trackingData.link} onChange={e => setTrackingData({...trackingData, link: e.target.value})} placeholder="https://..." className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" />
                        </div>
                        <div className="flex gap-3 pt-4 border-t border-slate-100">
                            <Button variant="secondary" type="button" onClick={routerCloseLayer} disabled={isSaving} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button type="submit" variant="primary" disabled={isSaving || !trackingData.number} className="flex-1 py-3 uppercase tracking-widest justify-center">Confirmer</Button>
                        </div>
                    </form>
                </Modal>
            )}

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

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