/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Modale de gestion des liens de saisie déléguée
 * =========================================================================
 */

const { useState } = React;

window.pano_ClientDelegateShareModal = ({ managingPanneau, setManagingPanneau, onClose, refreshData, showToast }) => {
    const { activeDialog, openDialog, closeCurrentLayer } = window.pano_useUrlModal();
    const routerCloseLayer = onClose || closeCurrentLayer;

    const {
        PlusIcon, LockIcon, CopyIcon, Trash2Icon, LinkIcon
    } = window.pano_getIcons();
    
    const Modal = window.pano_Modal;
    const AlertBox = window.pano_AlertBox;
    const EmptyState = window.pano_EmptyState;
    const Toggle = window.pano_Toggle;
    const ConfirmModal = window.pano_ConfirmModal;
    const Button = window.pano_Button;

    const [newLink, setNewLink] = useState({ name: '', expDays: 7, lockedFields: [] });
    const [isSaving, setIsSaving] = useState(false);
    const [confirmConfig, setConfirmConfig] = useState(null);

    const isDirty = newLink.name.trim() !== '' || newLink.expDays !== 7 || newLink.lockedFields.length > 0;

    return (
        <Modal title="Saisie déléguée" type="black" onClose={routerCloseLayer} requireConfirm={isDirty} zIndex="z-[200]">
            <div className="space-y-6">
                <div className="text-xs text-slate-500 mb-2"><span className="text-red-500 font-black">*</span> Champs obligatoires</div>
                
                <AlertBox type="info" icon={LockIcon}>
                    Créez des liens sécurisés pour confier la saisie d'informations ou le dépôt de documents (PDF) à d'autres membres de l'équipe du chantier sans leur donner accès à votre compte ou à votre facturation.
                </AlertBox>

                <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm space-y-4">
                    <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2"><PlusIcon size={16}/> Créer un nouveau lien</h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="space-y-1">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Nom du destinataire <span className="text-red-500 font-black">*</span></label>
                            <input value={newLink.name} onChange={e=>setNewLink({...newLink, name: e.target.value})} placeholder="Ex: Architecte Dupont" className="w-full border border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-blue-500 font-bold" />
                        </div>
                        <div className="space-y-1">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Validité (jours)</label>
                            <input type="number" min="1" max="90" value={newLink.expDays} onChange={e=>setNewLink({...newLink, expDays: parseInt(e.target.value)||7})} className="w-full border border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-blue-500 font-bold" />
                        </div>
                    </div>
                    <div className="space-y-2 pt-2">
                        <label className="text-xs font-bold text-slate-500 uppercase block">Verrouiller la saisie de ces champs (lecture seule) :</label>
                        <div className="flex flex-wrap gap-2">
                            {[
                                { id: 'name', label: 'Nom du chantier' }, { id: 'location', label: 'Lieu' },
                                { id: 'maitreOuvrage', label: "Maître d'ouvrage" }, { id: 'permitNumber', label: 'N° de permis' },
                                { id: 'description', label: 'Description' }, { id: 'promoterLink', label: 'Lien promoteur' },
                                { id: 'emergencyPhone', label: 'N° d\'urgence' }, { id: 'noiseSchedule', label: 'Horaires' },
                                { id: 'intervenants', label: 'Intervenants' }, { id: 'lots', label: 'Lots' }, { id: 'pdfId', label: 'Arrêté (PDF)' }
                            ].map(f => (
                                <div role="button" tabIndex={0} key={f.id} onClick={() => setNewLink(p => ({...p, lockedFields: p.lockedFields.includes(f.id) ? p.lockedFields.filter(x=>x!==f.id) : [...p.lockedFields, f.id]}))} className={`px-3 py-1.5 rounded-lg text-xs font-bold transition border cursor-pointer ${newLink.lockedFields.includes(f.id) ? 'bg-red-50 text-red-600 border-red-200' : 'bg-slate-50 text-slate-500 border-slate-200 hover:bg-slate-100'}`}>
                                    {newLink.lockedFields.includes(f.id) && <LockIcon size={12} className="inline mr-1"/>}{f.label}
                                </div>
                            ))}
                        </div>
                    </div>
                    <Button variant="primary" onClick={async () => {
                        if (!newLink.name.trim()) return showToast("Le nom du lien est obligatoire.", "error");
                        
                        const linkId = crypto.randomUUID();
                        const expTime = Math.floor(Date.now() / 1000) + (newLink.expDays * 86400);
                        const linkObj = { id: linkId, name: newLink.name.trim(), exp: expTime, active: true, lockedFields: newLink.lockedFields };
                        const updatedPanneau = { ...managingPanneau, delegate_links: [...(managingPanneau.delegate_links || []), linkObj] };
                        
                        const d = await window.pano_apiFetch('panneaux', { 
                            body: { id: updatedPanneau.id, status: updatedPanneau.status, offerType: updatedPanneau.offerType, physicalPanels: updatedPanneau.physicalPanels, details: updatedPanneau },
                            setLoading: setIsSaving,
                            successMessage: "Nouveau lien de saisie créé."
                        });
                        
                        if (d) {
                            setManagingPanneau(updatedPanneau);
                            setNewLink({ name: '', expDays: 7, lockedFields: [] });
                            if (refreshData) refreshData();
                        }
                    }} disabled={isSaving || !newLink.name.trim()} icon={PlusIcon} className="w-full py-3 justify-center uppercase tracking-widest text-xs">
                        Créer le lien
                    </Button>
                </div>

                <div className="space-y-3">
                    <h4 className="font-bold text-slate-800 text-sm">Liens générés pour ce panneau</h4>
                    
                    {(!managingPanneau.delegate_links || managingPanneau.delegate_links.length === 0) && (
                        <EmptyState icon={LinkIcon} text="Aucun lien n'a encore été créé pour ce panneau." />
                    )}

                    {managingPanneau.delegate_links?.map((link, idx) => {
                        const isExpired = link.exp < Date.now() / 1000;
                        return (
                            <div key={idx} className={`p-4 rounded-xl border ${link.active && !isExpired ? 'bg-white border-slate-200 shadow-sm' : 'bg-slate-50 border-slate-200 opacity-75'}`}>
                                <div className="flex justify-between items-start mb-2">
                                    <div>
                                        <p className="font-bold text-slate-800 text-sm">{link.name}</p>
                                        <p className="text-xs text-slate-500">Exp. : {new Date(link.exp * 1000).toLocaleDateString('fr-FR')} {isExpired && <span className="text-red-500 font-bold ml-1">(Expiré)</span>}</p>
                                    </div>
                                    <div className="flex items-center gap-3">
                                        
                                        <Toggle 
                                            checked={link.active} 
                                            onChange={async (newVal) => {
                                                const links = [...managingPanneau.delegate_links];
                                                links[idx] = { ...links[idx], active: newVal };
                                                const updatedPanneau = { ...managingPanneau, delegate_links: links };
                                                
                                                const d = await window.pano_apiFetch('panneaux', { 
                                                    body: { id: updatedPanneau.id, status: updatedPanneau.status, offerType: updatedPanneau.offerType, physicalPanels: updatedPanneau.physicalPanels, details: updatedPanneau },
                                                    setLoading: setIsSaving
                                                });
                                                
                                                if (d) { 
                                                    setManagingPanneau(updatedPanneau); 
                                                    if (refreshData) refreshData(); 
                                                }
                                            }} 
                                        />

                                        <Button variant="secondary" shape="square" icon={CopyIcon} onClick={async () => {
                                            const d = await window.pano_apiFetch('panneaux/delegate_link', { 
                                                body: { id: managingPanneau.id, link_id: link.id },
                                                setLoading: setIsSaving 
                                            });
                                            if (d) { 
                                                navigator.clipboard.writeText(d.data.link); 
                                                showToast("Lien copié !", "success"); 
                                            }
                                        }} disabled={!link.active || isExpired || isSaving} title="Copier l'URL" className="p-2" />
                                        
                                        <Button variant="danger" shape="round" icon={Trash2Icon} onClick={(e) => {
                                            e.stopPropagation();
                                            setConfirmConfig({
                                                title: "Supprimer le lien",
                                                message: "Voulez-vous vraiment supprimer ce lien délégué ?",
                                                confirmText: "Supprimer",
                                                isDestructive: true,
                                                onConfirm: async () => {
                                                    setConfirmConfig(null);
                                                    closeCurrentLayer();
                                                    
                                                    const links = [...managingPanneau.delegate_links];
                                                    links.splice(idx, 1);
                                                    const updatedPanneau = { ...managingPanneau, delegate_links: links };
                                                    
                                                    const d = await window.pano_apiFetch('panneaux', { 
                                                        body: { id: updatedPanneau.id, status: updatedPanneau.status, offerType: updatedPanneau.offerType, physicalPanels: updatedPanneau.physicalPanels, details: updatedPanneau },
                                                        setLoading: setIsSaving
                                                    });
                                                    
                                                    if (d) { 
                                                        setManagingPanneau(updatedPanneau); 
                                                        if (refreshData) refreshData(); 
                                                    }
                                                }
                                            });
                                            openDialog('confirm');
                                        }} className="p-2 shadow-none" title="Supprimer" />
                                    </div>
                                </div>
                                {link.lockedFields && link.lockedFields.length > 0 && (
                                    <p className="text-[10px] text-slate-500 mt-2 border-t border-slate-100 pt-2"><LockIcon size={10} className="inline mr-1"/> Verrouillés : {link.lockedFields.join(', ')}</p>
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>

            {activeDialog === 'confirm' && confirmConfig && ConfirmModal && (
                <ConfirmModal 
                    {...confirmConfig} 
                    onCancel={() => {
                        setConfirmConfig(null);
                        closeCurrentLayer();
                    }} 
                    zIndex="z-[350]" 
                />
            )}
        </Modal>
    );
};

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