import React, { useEffect, useMemo, useState } from 'react';
import { api } from '../lib/api';
import { toast } from 'sonner';
import {
    X, Mail, Send, Settings as SettingsIcon, Plus, Pencil, Trash2, Save,
    Image as ImageIcon, CheckSquare, Square,
} from 'lucide-react';

/**
 * Modale "Envoyer par email" pour un dossier camion.
 * - Pré-remplit destinataires SAV + Quai (configurables via gear)
 * - Choix d'un modèle de texte
 * - Sélection de photos → URLs publiques signées (HMAC, 30j)
 * - Bouton final : ouvre mailto: avec tout pré-rempli
 *
 * Props:
 *  - folder: objet dossier (id, plate, numero_em_sm, type_em_sm, cariste_name, contributions)
 *  - onClose()
 *  - currentUser: pour le check can_manage_folder_email côté frontend (le backend vérifie aussi)
 */
export default function FolderEmailModal({ folder, onClose, currentUser }) {
    const [cfg, setCfg] = useState(null);   // { to_sav, to_quai, subject_prefix, templates, can_manage }
    const [loadingCfg, setLoadingCfg] = useState(true);
    const [editingSettings, setEditingSettings] = useState(false);
    const [toSav, setToSav] = useState('');
    const [toQuai, setToQuai] = useState('');
    const [subjectExtra, setSubjectExtra] = useState('');
    const [templateId, setTemplateId] = useState(null);
    const [body, setBody] = useState('');
    const [includeCariste, setIncludeCariste] = useState(true);
    const [selectedPositions, setSelectedPositions] = useState(new Set());
    const [busy, setBusy] = useState(false);

    // Build flat list of photos with their global position (matches DB position order)
    const allPhotos = useMemo(() => {
        const out = [];
        const contribs = folder?.contributions || [];
        let pos = 0;
        for (const c of contribs) {
            for (const data of (c.photos || [])) {
                out.push({ position: pos, data, by_name: c.by_name, at: c.at });
                pos += 1;
            }
        }
        return out;
    }, [folder]);

    // Cariste comment = problem + summary of all appended texts
    const caristeComment = useMemo(() => {
        const contribs = folder?.contributions || [];
        const parts = [];
        for (const c of contribs) {
            const txt = (c.text || '').trim();
            if (txt) parts.push(`— ${c.by_name || 'Cariste'} :\n${txt}`);
        }
        return parts.join('\n\n');
    }, [folder]);

    const loadCfg = async () => {
        setLoadingCfg(true);
        try {
            const r = await api.get('/folder-email/config');
            setCfg(r.data);
            setToSav(r.data?.to_sav || '');
            setToQuai(r.data?.to_quai || '');
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur chargement config email');
        } finally { setLoadingCfg(false); }
    };
    useEffect(() => { loadCfg(); }, []);

    const applyTemplate = (tpl) => {
        setTemplateId(tpl?.id || null);
        setBody(tpl?.body || '');
    };

    const togglePhoto = (pos) => {
        setSelectedPositions((prev) => {
            const next = new Set(prev);
            if (next.has(pos)) next.delete(pos);
            else next.add(pos);
            return next;
        });
    };

    const toggleAll = () => {
        if (selectedPositions.size === allPhotos.length) {
            setSelectedPositions(new Set());
        } else {
            setSelectedPositions(new Set(allPhotos.map((p) => p.position)));
        }
    };

    const subject = useMemo(() => {
        // v7 : préfixe auto EM/SM depuis folder.type_em_sm + immatriculation
        // REMORQUE (pas tracteur) + slash final prêt pour saisie manuelle.
        const detectedType = (folder?.type_em_sm || '').trim().toUpperCase();
        const prefix = (detectedType === 'EM' || detectedType === 'SM')
            ? detectedType
            : (cfg?.subject_prefix || 'EM').trim();
        const num = (folder?.numero_em_sm || '').trim();
        const remorque = (folder?.immatriculation_remorque || '').trim();
        // ex : "EM 1418921 / RZ-789-AB / <extra-saisi-manuellement>"
        const base = num ? `${prefix} ${num}` : prefix;
        const auto = remorque ? `/ ${remorque}` : '';
        const extra = (subjectExtra || '').trim();
        const parts = [base, auto, extra ? `/ ${extra}` : (remorque ? '/' : '')];
        return parts.filter(Boolean).join(' ').trim();
    }, [cfg, folder, subjectExtra]);

    const handleSend = async () => {
        const recipients = [toSav.trim(), toQuai.trim()].filter(Boolean);
        if (!recipients.length) {
            toast.error('Au moins un destinataire requis (SAV ou Quai)');
            return;
        }
        setBusy(true);
        try {
            // 1. Sign selected photos (HMAC links, 30 jours, sans auth)
            let photoLinks = '';
            if (selectedPositions.size > 0) {
                const r = await api.post(
                    `/folders/${folder.id}/email/sign-photos`,
                    { positions: Array.from(selectedPositions) },
                );
                const origin = window.location.origin;
                const lines = (r.data?.photos || []).map((p, i) =>
                    `Photo ${i + 1} : ${origin}${p.url}`,
                );
                if (lines.length) {
                    const ttl = r.data?.ttl_days || 30;
                    photoLinks = `\n\nPhotos (liens valides ${ttl} jours, sans connexion) :\n${lines.join('\n')}`;
                }
            }
            // 2. Build final body
            const sections = [];
            if (body.trim()) sections.push(body.trim());
            if (includeCariste && caristeComment) {
                sections.push(`Commentaires cariste :\n${caristeComment}`);
            }
            const fullBody = sections.join('\n\n') + photoLinks;

            // 3. Compose mailto
            const to = recipients.join(',');
            const mailto = `mailto:${encodeURIComponent(to)}` +
                `?subject=${encodeURIComponent(subject)}` +
                `&body=${encodeURIComponent(fullBody)}`;
            window.location.href = mailto;
            toast.success('Outlook va s\'ouvrir avec l\'email pré-rempli');
            // Close after a short delay so the mailto: handler has time to trigger
            setTimeout(() => onClose(), 600);
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur préparation email');
        } finally { setBusy(false); }
    };

    if (loadingCfg) {
        return (
            <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" data-testid="folder-email-modal">
                <div className="bg-white rounded-lg shadow-xl p-10 text-slate-500">Chargement…</div>
            </div>
        );
    }

    return (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-start sm:items-center justify-center p-4 overflow-y-auto" data-testid="folder-email-modal">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl my-8">
                <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200">
                    <h2 className="font-heading text-lg font-black text-slate-900 flex items-center gap-2">
                        <Mail className="h-5 w-5 text-stef" /> Envoyer par email
                    </h2>
                    <div className="flex items-center gap-1">
                        {cfg?.can_manage && (
                            <button
                                data-testid="folder-email-gear"
                                onClick={() => setEditingSettings(true)}
                                className="h-8 w-8 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500"
                                title="Paramètres email (admin)"
                            >
                                <SettingsIcon className="h-4 w-4" />
                            </button>
                        )}
                        <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500" data-testid="folder-email-close">
                            <X className="h-5 w-5" />
                        </button>
                    </div>
                </div>

                <div className="px-5 py-4 space-y-4 max-h-[75vh] overflow-y-auto">
                    {/* Destinataires + objet */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Email SAV</label>
                            <input
                                data-testid="folder-email-to-sav"
                                value={toSav}
                                onChange={(e) => setToSav(e.target.value)}
                                placeholder="sav@exemple.fr"
                                className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                            />
                        </div>
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Email Quai</label>
                            <input
                                data-testid="folder-email-to-quai"
                                value={toQuai}
                                onChange={(e) => setToQuai(e.target.value)}
                                placeholder="quai@exemple.fr"
                                className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                            />
                        </div>
                    </div>

                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Objet de l&apos;email</label>
                        <div className="mt-1.5 flex items-center gap-2">
                            <span data-testid="folder-email-subject-prefix" className="inline-flex items-center rounded-md bg-stef/10 text-stef px-3 h-11 text-sm font-bold whitespace-nowrap">
                                {subject}
                            </span>
                            <input
                                data-testid="folder-email-subject-extra"
                                value={subjectExtra}
                                onChange={(e) => setSubjectExtra(e.target.value)}
                                placeholder="Ajouter (facultatif)…"
                                className="flex-1 h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                            />
                        </div>
                        <p className="mt-1 text-[11px] text-slate-500">
                            L&apos;objet est généré depuis le préfixe (configurable) + n° EM/SM du dossier.
                        </p>
                    </div>

                    {/* Templates */}
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Modèle de texte</label>
                        <div className="mt-1.5 flex flex-wrap gap-1.5">
                            <button
                                data-testid="folder-email-tpl-none"
                                onClick={() => applyTemplate(null)}
                                className={`rounded-full border px-3 h-8 text-xs font-bold transition ${
                                    templateId === null
                                        ? 'bg-stef text-white border-stef'
                                        : 'bg-white text-slate-700 border-slate-300 hover:border-stef hover:text-stef'
                                }`}
                            >
                                Aucun
                            </button>
                            {(cfg?.templates || []).map((tpl) => (
                                <button
                                    key={tpl.id}
                                    data-testid={`folder-email-tpl-${tpl.id}`}
                                    onClick={() => applyTemplate(tpl)}
                                    className={`rounded-full border px-3 h-8 text-xs font-bold transition ${
                                        templateId === tpl.id
                                            ? 'bg-stef text-white border-stef'
                                            : 'bg-white text-slate-700 border-slate-300 hover:border-stef hover:text-stef'
                                    }`}
                                >
                                    {tpl.label}
                                </button>
                            ))}
                            {(cfg?.templates || []).length === 0 && (
                                <p className="text-xs text-slate-500 italic py-1.5">
                                    Aucun modèle. {cfg?.can_manage && 'Clique sur l\'engrenage pour en créer.'}
                                </p>
                            )}
                        </div>
                    </div>

                    {/* Body */}
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Corps du message</label>
                        <textarea
                            data-testid="folder-email-body"
                            value={body}
                            onChange={(e) => setBody(e.target.value)}
                            rows={6}
                            placeholder="Écris ton message…"
                            className="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 font-mono"
                        />
                    </div>

                    {/* Cariste comment */}
                    {caristeComment && (
                        <div className="rounded-md border border-stef/30 bg-stef/5 p-3">
                            <label className="inline-flex items-center gap-2 cursor-pointer">
                                <input
                                    type="checkbox"
                                    data-testid="folder-email-include-cariste"
                                    checked={includeCariste}
                                    onChange={(e) => setIncludeCariste(e.target.checked)}
                                    className="h-4 w-4 rounded border-stef/50 text-stef focus:ring-stef/30"
                                />
                                <span className="text-xs font-bold uppercase tracking-wider text-stef">
                                    Inclure les commentaires du cariste
                                </span>
                            </label>
                            {includeCariste && (
                                <pre className="mt-2 text-[12px] text-slate-700 whitespace-pre-wrap font-sans">{caristeComment}</pre>
                            )}
                        </div>
                    )}

                    {/* Photos */}
                    <div>
                        <div className="flex items-center justify-between">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">
                                Photos à joindre ({selectedPositions.size}/{allPhotos.length})
                            </label>
                            {allPhotos.length > 0 && (
                                <button
                                    data-testid="folder-email-toggle-all-photos"
                                    onClick={toggleAll}
                                    className="text-xs font-bold text-stef hover:underline"
                                >
                                    {selectedPositions.size === allPhotos.length ? 'Tout désélectionner' : 'Tout sélectionner'}
                                </button>
                            )}
                        </div>
                        {allPhotos.length === 0 ? (
                            <div className="mt-2 rounded-md border border-dashed border-slate-300 bg-slate-50 p-6 text-center">
                                <ImageIcon className="mx-auto h-8 w-8 text-slate-300" />
                                <p className="mt-2 text-xs text-slate-500">Aucune photo dans ce dossier</p>
                            </div>
                        ) : (
                            <div className="mt-2 grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
                                {allPhotos.map((p) => {
                                    const selected = selectedPositions.has(p.position);
                                    return (
                                        <button
                                            key={p.position}
                                            data-testid={`folder-email-photo-${p.position}`}
                                            onClick={() => togglePhoto(p.position)}
                                            className={`relative aspect-square rounded-md overflow-hidden border-2 transition ${
                                                selected ? 'border-stef ring-2 ring-stef/30' : 'border-slate-200 hover:border-stef/50'
                                            }`}
                                        >
                                            <img src={p.data} alt="" className="absolute inset-0 h-full w-full object-cover" />
                                            <span className={`absolute top-1 right-1 h-5 w-5 rounded flex items-center justify-center text-white ${
                                                selected ? 'bg-stef' : 'bg-black/40'
                                            }`}>
                                                {selected ? <CheckSquare className="h-3.5 w-3.5" /> : <Square className="h-3.5 w-3.5" />}
                                            </span>
                                        </button>
                                    );
                                })}
                            </div>
                        )}
                        <p className="mt-1 text-[11px] text-slate-500">
                            Les photos cochées sont jointes via des liens publics signés (valides 30 jours, pas besoin de se connecter pour les voir).
                        </p>
                    </div>
                </div>

                <div className="px-5 py-3 border-t border-slate-200 flex items-center justify-between gap-2">
                    <p className="text-[11px] text-slate-500">
                        Cliquer sur &laquo;&nbsp;Ouvrir Outlook&nbsp;&raquo; lancera ton client mail par défaut.
                    </p>
                    <div className="flex gap-2">
                        <button onClick={onClose} className="rounded-md border border-slate-300 px-4 h-10 text-sm font-bold hover:bg-slate-50" data-testid="folder-email-cancel">
                            Annuler
                        </button>
                        <button
                            data-testid="folder-email-send"
                            onClick={handleSend}
                            disabled={busy}
                            className="inline-flex items-center gap-2 rounded-md bg-stef text-white px-5 h-10 text-sm font-heading font-bold hover:bg-stef-hover active:scale-[0.99] transition-all disabled:opacity-60"
                        >
                            <Send className="h-4 w-4" /> {busy ? 'Préparation…' : 'Ouvrir Outlook'}
                        </button>
                    </div>
                </div>
            </div>

            {editingSettings && (
                <FolderEmailSettingsModal
                    cfg={cfg}
                    onClose={() => setEditingSettings(false)}
                    onSaved={(newCfg) => {
                        setCfg(newCfg);
                        setToSav(newCfg.to_sav || '');
                        setToQuai(newCfg.to_quai || '');
                    }}
                />
            )}
        </div>
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Sub-modal: gear icon → edit SAV/Quai recipients + CRUD templates
// ─────────────────────────────────────────────────────────────────────────────
function FolderEmailSettingsModal({ cfg, onClose, onSaved }) {
    const [toSav, setToSav] = useState(cfg?.to_sav || '');
    const [toQuai, setToQuai] = useState(cfg?.to_quai || '');
    const [subjectPrefix, setSubjectPrefix] = useState(cfg?.subject_prefix || 'EM');
    const [templates, setTemplates] = useState(cfg?.templates || []);
    const [editingTpl, setEditingTpl] = useState(null); // { id?, label, body, sort_order }
    const [savingCfg, setSavingCfg] = useState(false);

    const saveCfg = async () => {
        setSavingCfg(true);
        try {
            const r = await api.put('/folder-email/settings', {
                to_sav: toSav, to_quai: toQuai, subject_prefix: subjectPrefix,
            });
            toast.success('Paramètres email mis à jour');
            onSaved({ ...cfg, ...r.data, templates });
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur');
        } finally { setSavingCfg(false); }
    };

    const saveTpl = async (tpl) => {
        try {
            const payload = {
                label: tpl.label || '',
                body: tpl.body || '',
                sort_order: Number(tpl.sort_order || 0),
            };
            if (tpl.id) {
                const r = await api.patch(`/folder-email/templates/${tpl.id}`, payload);
                setTemplates((arr) => arr.map((x) => (x.id === tpl.id ? r.data : x)));
                toast.success('Modèle mis à jour');
            } else {
                const r = await api.post('/folder-email/templates', payload);
                setTemplates((arr) => [...arr, r.data]);
                toast.success('Modèle créé');
            }
            setEditingTpl(null);
            onSaved({ ...cfg, to_sav: toSav, to_quai: toQuai, subject_prefix: subjectPrefix,
                templates: tpl.id
                    ? templates.map((x) => (x.id === tpl.id ? { ...x, ...tpl } : x))
                    : [...templates, { ...tpl, id: Date.now() }] });
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur');
        }
    };

    const delTpl = async (id) => {
        if (!window.confirm('Supprimer ce modèle ?')) return;
        try {
            await api.delete(`/folder-email/templates/${id}`);
            setTemplates((arr) => arr.filter((x) => x.id !== id));
            toast.success('Modèle supprimé');
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur');
        }
    };

    return (
        <div className="fixed inset-0 z-[60] bg-black/50 flex items-start sm:items-center justify-center p-4 overflow-y-auto" data-testid="folder-email-settings-modal">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl my-8">
                <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200">
                    <h2 className="font-heading text-lg font-black text-slate-900 flex items-center gap-2">
                        <SettingsIcon className="h-5 w-5 text-stef" /> Paramètres email Dossiers
                    </h2>
                    <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500" data-testid="folder-email-settings-close">
                        <X className="h-5 w-5" />
                    </button>
                </div>

                <div className="px-5 py-4 space-y-5 max-h-[75vh] overflow-y-auto">
                    {/* Destinataires */}
                    <section>
                        <h3 className="text-xs font-bold uppercase tracking-wider text-slate-500 mb-3">Destinataires par défaut</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div>
                                <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Email SAV</label>
                                <input
                                    data-testid="folder-email-settings-sav"
                                    value={toSav}
                                    onChange={(e) => setToSav(e.target.value)}
                                    placeholder="sav@stef.com"
                                    className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                />
                            </div>
                            <div>
                                <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Email Quai</label>
                                <input
                                    data-testid="folder-email-settings-quai"
                                    value={toQuai}
                                    onChange={(e) => setToQuai(e.target.value)}
                                    placeholder="quai@stef.com"
                                    className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                />
                            </div>
                            <div>
                                <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Préfixe objet</label>
                                <input
                                    data-testid="folder-email-settings-prefix"
                                    value={subjectPrefix}
                                    onChange={(e) => setSubjectPrefix(e.target.value)}
                                    placeholder="EM"
                                    className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                />
                                <p className="mt-1 text-[11px] text-slate-500">Sera suivi du n° EM/SM du dossier.</p>
                            </div>
                            <div className="flex items-end">
                                <button
                                    data-testid="folder-email-settings-save"
                                    onClick={saveCfg}
                                    disabled={savingCfg}
                                    className="inline-flex items-center gap-2 rounded-md bg-stef text-white px-5 h-11 text-sm font-heading font-bold hover:bg-stef-hover disabled:opacity-60"
                                >
                                    <Save className="h-4 w-4" /> {savingCfg ? 'Enregistrement…' : 'Enregistrer destinataires'}
                                </button>
                            </div>
                        </div>
                    </section>

                    {/* Templates */}
                    <section>
                        <div className="flex items-center justify-between mb-3">
                            <h3 className="text-xs font-bold uppercase tracking-wider text-slate-500">Modèles de texte</h3>
                            <button
                                data-testid="folder-email-tpl-new"
                                onClick={() => setEditingTpl({ id: null, label: '', body: '', sort_order: templates.length })}
                                className="inline-flex items-center gap-1.5 rounded-md bg-stef text-white px-3 h-9 text-xs font-bold hover:bg-stef-hover"
                            >
                                <Plus className="h-3.5 w-3.5" /> Nouveau modèle
                            </button>
                        </div>
                        {templates.length === 0 ? (
                            <div className="rounded-md border border-dashed border-slate-300 bg-slate-50 p-6 text-center">
                                <p className="text-xs text-slate-500">Aucun modèle. Crée ton premier modèle pour gagner du temps.</p>
                            </div>
                        ) : (
                            <ul className="divide-y divide-slate-100 border border-slate-200 rounded-md overflow-hidden">
                                {templates.map((t) => (
                                    <li key={t.id} className="px-3 py-2.5 flex items-start justify-between gap-2 hover:bg-slate-50" data-testid={`folder-email-tpl-row-${t.id}`}>
                                        <div className="min-w-0 flex-1">
                                            <p className="font-bold text-sm text-slate-900 truncate">{t.label}</p>
                                            <p className="text-xs text-slate-500 line-clamp-2 whitespace-pre-line">{t.body}</p>
                                        </div>
                                        <div className="flex gap-1 shrink-0">
                                            <button
                                                data-testid={`folder-email-tpl-edit-${t.id}`}
                                                onClick={() => setEditingTpl({ ...t })}
                                                className="h-8 w-8 rounded-md hover:bg-stef/10 text-stef flex items-center justify-center"
                                                title="Éditer"
                                            >
                                                <Pencil className="h-3.5 w-3.5" />
                                            </button>
                                            <button
                                                data-testid={`folder-email-tpl-delete-${t.id}`}
                                                onClick={() => delTpl(t.id)}
                                                className="h-8 w-8 rounded-md hover:bg-red-50 text-red-600 flex items-center justify-center"
                                                title="Supprimer"
                                            >
                                                <Trash2 className="h-3.5 w-3.5" />
                                            </button>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </section>
                </div>

                <div className="px-5 py-3 border-t border-slate-200 flex justify-end">
                    <button onClick={onClose} className="rounded-md border border-slate-300 px-4 h-10 text-sm font-bold hover:bg-slate-50">Fermer</button>
                </div>
            </div>

            {editingTpl && (
                <TemplateEditorModal
                    tpl={editingTpl}
                    onChange={setEditingTpl}
                    onSave={() => saveTpl(editingTpl)}
                    onClose={() => setEditingTpl(null)}
                />
            )}
        </div>
    );
}

function TemplateEditorModal({ tpl, onChange, onSave, onClose }) {
    return (
        <div className="fixed inset-0 z-[70] bg-black/50 flex items-start sm:items-center justify-center p-4 overflow-y-auto" data-testid="folder-email-tpl-editor">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-xl my-8">
                <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200">
                    <h2 className="font-heading text-lg font-black text-slate-900">
                        {tpl.id ? 'Modifier le modèle' : 'Nouveau modèle'}
                    </h2>
                    <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500" data-testid="folder-email-tpl-editor-close">
                        <X className="h-5 w-5" />
                    </button>
                </div>
                <div className="px-5 py-4 space-y-3 max-h-[70vh] overflow-y-auto">
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Libellé *</label>
                        <input
                            data-testid="folder-email-tpl-label"
                            value={tpl.label}
                            onChange={(e) => onChange({ ...tpl, label: e.target.value })}
                            placeholder="ex. Casse, Manquant, Mauvais destinataire…"
                            className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                        />
                    </div>
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Texte *</label>
                        <textarea
                            data-testid="folder-email-tpl-body"
                            value={tpl.body}
                            onChange={(e) => onChange({ ...tpl, body: e.target.value })}
                            rows={8}
                            placeholder="Bonjour,&#10;&#10;Veuillez trouver ci-joint…"
                            className="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 font-mono"
                        />
                    </div>
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Ordre d&apos;affichage</label>
                        <input
                            data-testid="folder-email-tpl-order"
                            type="number"
                            value={tpl.sort_order ?? 0}
                            onChange={(e) => onChange({ ...tpl, sort_order: e.target.value })}
                            className="mt-1.5 w-32 h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                        />
                    </div>
                </div>
                <div className="px-5 py-3 border-t border-slate-200 flex justify-end gap-2">
                    <button onClick={onClose} className="rounded-md border border-slate-300 px-4 h-10 text-sm font-bold hover:bg-slate-50">Annuler</button>
                    <button
                        data-testid="folder-email-tpl-save"
                        onClick={onSave}
                        className="inline-flex items-center gap-2 rounded-md bg-stef text-white px-5 h-10 text-sm font-heading font-bold hover:bg-stef-hover"
                    >
                        <Save className="h-4 w-4" /> Enregistrer
                    </button>
                </div>
            </div>
        </div>
    );
}
