import React, { useEffect, useRef, useState } from 'react';
import Layout from '../components/Layout';
import { useNavigate } from 'react-router-dom';
import { api } from '../lib/api';
import { toast } from 'sonner';
import { Camera, ImagePlus, X, FolderPlus, Truck, Zap, CheckCircle2, RotateCcw } from 'lucide-react';
import { resizeImage } from '../lib/image';
import { cleanPlate, PLATE_MAX_LEN } from '../lib/plate';

const MAX_PHOTOS = 30;

// xdockMode lifecycle:
//   'detecting'  : initial probe en cours
//   'pending'    : camion détecté, en attente de Valider/Refuser
//   'validated'  : cariste a validé → champs verrouillés (readOnly)
//   'manual'     : pas de détection OU refus → saisie libre
export default function NewFolder() {
    const navigate = useNavigate();
    const [plate, setPlate] = useState('');
    const [remorque, setRemorque] = useState('');
    const [problem, setProblem] = useState('');
    const [numeroEmSm, setNumeroEmSm] = useState('');
    const [typeEmSm, setTypeEmSm] = useState('');
    const [photos, setPhotos] = useState([]);
    const [phrases, setPhrases] = useState([]);
    const [submitting, setSubmitting] = useState(false);
    const [xdockMode, setXdockMode] = useState('detecting');
    const [xdockProposal, setXdockProposal] = useState(null); // { tracteur, remorque, tour_number, tour_type, source, last_seen }
    const galleryRef = useRef(null);
    const cameraRef = useRef(null);

    useEffect(() => {
        api.get('/phrases').then(r => setPhrases(r.data)).catch(() => {});
    }, []);

    // XDock detection: server-side cache first, then bridge fallback
    useEffect(() => {
        let cancelled = false;
        const detect = async () => {
            // 1) Try server-side cache (extension POSTs there)
            try {
                const r = await api.get('/xdock/current-task/me');
                if (cancelled) return;
                if (r.data?.found && r.data?.data) {
                    const d = r.data.data;
                    if (d.tracteur || d.remorque || d.tour_number) {
                        setXdockProposal({ ...d, source: 'server' });
                        setXdockMode('pending');
                        return;
                    }
                }
            } catch (_) { /* swallow */ }
            // 2) Fallback: in-page bridge (XDockPlusBridge.findCurrentTruck)
            try {
                if (window.XDockPlusBridge && typeof window.XDockPlusBridge.findCurrentTruck === 'function') {
                    const me = await api.get('/me/xdock');
                    if (cancelled) return;
                    if (me.data?.success) {
                        const result = await window.XDockPlusBridge.findCurrentTruck({ xdock_name: me.data.xdock_name });
                        if (cancelled) return;
                        if (result?.found) {
                            setXdockProposal({
                                tracteur: result.tracteur || '',
                                remorque: result.remorque || '',
                                tour_number: result.tour_number || '',
                                tour_type: result.tour_type || '',
                                source: 'bridge',
                                last_seen: null,
                            });
                            setXdockMode('pending');
                            return;
                        }
                    }
                }
            } catch (_) { /* swallow */ }
            // 3) No detection → manual mode
            if (!cancelled) setXdockMode('manual');
        };
        detect();
        return () => { cancelled = true; };
    }, []);

    const acceptXdock = () => {
        if (!xdockProposal) return;
        setPlate(cleanPlate(xdockProposal.tracteur || ''));
        setRemorque(cleanPlate(xdockProposal.remorque || ''));
        setNumeroEmSm(String(xdockProposal.tour_number || ''));
        setTypeEmSm(String(xdockProposal.tour_type || '').toUpperCase());
        setXdockMode('validated');
        toast.success('Camion validé — informations verrouillées');
    };

    const refuseXdock = () => {
        setPlate('');
        setRemorque('');
        setNumeroEmSm('');
        setTypeEmSm('');
        setXdockMode('manual');
        toast.info('Saisie manuelle activée');
    };

    const unlockXdock = () => {
        // Permet de revenir en saisie manuelle même après validation (au cas où le cariste s'est trompé)
        setXdockMode('manual');
        toast.info('Champs déverrouillés — saisie manuelle');
    };

    const handleFiles = async (files) => {
        const arr = Array.from(files);
        const remaining = MAX_PHOTOS - photos.length;
        if (remaining <= 0) {
            toast.error(`Maximum ${MAX_PHOTOS} photos`);
            return;
        }
        const toProcess = arr.slice(0, remaining);
        const results = [];
        for (const f of toProcess) {
            try {
                const url = await resizeImage(f);
                results.push(url);
            } catch (_) { /* skip */ }
        }
        setPhotos((p) => [...p, ...results]);
    };

    const removePhoto = (i) => setPhotos((p) => p.filter((_, idx) => idx !== i));

    const appendPhrase = (text) => {
        setProblem((prev) => (prev ? prev + (prev.endsWith('\n') ? '' : '\n') + text : text));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!plate.trim()) { toast.error('Plaque tracteur requise'); return; }
        if (!problem.trim()) { toast.error('Description requise'); return; }
        setSubmitting(true);
        try {
            const res = await api.post('/folders', {
                plate,
                problem,
                photos,
                numero_em_sm: numeroEmSm.trim(),
                type_em_sm: typeEmSm.trim().toUpperCase(),
                immatriculation_remorque: (remorque || '').trim().toUpperCase(),
            });
            toast.success('Dossier créé');
            navigate(`/folders/${res.data.id}`);
        } catch (err) {
            // Anti-duplicate: an open folder already exists for this plate
            const status = err?.response?.status;
            const detail = err?.response?.data?.detail;
            if (status === 409 && detail && detail.code === 'duplicate_open_folder' && detail.folder_id) {
                toast.message('Dossier existant pour ce camion', {
                    description: 'Un dossier est déjà ouvert. Tu vas être redirigé(e) dessus pour ajouter ta mise à jour.',
                    duration: 4000,
                });
                setTimeout(() => navigate(`/folders/${detail.folder_id}?append=1`), 600);
                return;
            }
            toast.error(detail?.message || detail || 'Erreur création');
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Layout>
            <div className="max-w-3xl mx-auto">
                <div className="mb-6 sm:mb-8">
                    <p className="text-xs font-bold uppercase tracking-[0.2em] text-stef">Création</p>
                    <h1 className="mt-2 font-heading text-2xl sm:text-3xl lg:text-4xl font-black tracking-tight text-slate-900">Nouveau dossier</h1>
                    <p className="mt-1.5 text-sm sm:text-base text-slate-600">Renseigne la plaque, décris le problème. Les photos sont optionnelles (jusqu'à 30).</p>
                </div>

                {/* XDock — état "detecting" (loader très discret) */}
                {xdockMode === 'detecting' && (
                    <div data-testid="xdock-detecting" className="mb-5 rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 flex items-center gap-3 text-sm text-slate-500">
                        <span className="inline-block h-3 w-3 rounded-full bg-stef/40 animate-pulse" />
                        Détection du camion en cours via XDock…
                    </div>
                )}

                {/* XDock — état "pending" : carte de confirmation */}
                {xdockMode === 'pending' && xdockProposal && (
                    <div data-testid="xdock-confirm-card" className="mb-6 rounded-xl border-2 border-stef bg-white p-5 sm:p-6 shadow-lg shadow-stef/10">
                        <div className="flex items-center gap-3 mb-4">
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-stef/10 text-stef">
                                <Zap className="h-5 w-5" />
                            </div>
                            <div>
                                <p className="text-xs font-bold uppercase tracking-[0.18em] text-stef">Détecté via XDock</p>
                                <h2 className="font-heading text-lg font-black text-slate-900">Est-ce ton camion actuel&nbsp;?</h2>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-5">
                            <div className="rounded-lg border border-slate-200 bg-slate-50/50 px-4 py-3">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Plaque tracteur</p>
                                <p className="mt-1 font-heading text-lg font-black tracking-wider text-slate-900" data-testid="xdock-proposal-tracteur">
                                    {xdockProposal.tracteur || '—'}
                                </p>
                            </div>
                            <div className="rounded-lg border border-slate-200 bg-slate-50/50 px-4 py-3">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Plaque remorque</p>
                                <p className="mt-1 font-heading text-lg font-black tracking-wider text-slate-900" data-testid="xdock-proposal-remorque">
                                    {xdockProposal.remorque || '—'}
                                </p>
                            </div>
                            <div className="rounded-lg border border-slate-200 bg-slate-50/50 px-4 py-3">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">N° tournée</p>
                                <p className="mt-1 font-heading text-lg font-black tracking-wider text-slate-900" data-testid="xdock-proposal-tour">
                                    {xdockProposal.tour_number || '—'}
                                </p>
                            </div>
                            <div className="rounded-lg border border-slate-200 bg-slate-50/50 px-4 py-3">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Type</p>
                                <p className="mt-1 font-heading text-lg font-black tracking-wider text-slate-900" data-testid="xdock-proposal-type">
                                    {xdockProposal.tour_type || '—'}
                                </p>
                            </div>
                        </div>

                        <div className="flex flex-col sm:flex-row gap-3">
                            <button
                                type="button"
                                data-testid="xdock-accept-btn"
                                onClick={acceptXdock}
                                className="flex-1 h-12 rounded-md bg-stef text-white font-heading font-bold tracking-wide hover:bg-stef-hover active:scale-[0.99] transition-all flex items-center justify-center gap-2 shadow-md shadow-stef/20"
                            >
                                <CheckCircle2 className="h-5 w-5" />
                                Oui, c'est mon camion
                            </button>
                            <button
                                type="button"
                                data-testid="xdock-refuse-btn"
                                onClick={refuseXdock}
                                className="flex-1 h-12 rounded-md border border-slate-300 bg-white text-slate-700 font-heading font-bold hover:bg-slate-50 active:scale-[0.99] transition-all flex items-center justify-center gap-2"
                            >
                                <X className="h-4 w-4" />
                                Non, saisie manuelle
                            </button>
                        </div>
                    </div>
                )}

                {/* XDock — état "validated" : bandeau enrichi avec résumé du camion + bouton Modifier */}
                {xdockMode === 'validated' && (
                    <div data-testid="xdock-validated-banner" className="mb-5 rounded-xl border-2 border-emerald-300 bg-emerald-50 px-4 sm:px-5 py-4">
                        <div className="flex items-start gap-3">
                            <CheckCircle2 className="h-6 w-6 text-emerald-600 shrink-0 mt-0.5" />
                            <div className="flex-1 min-w-0">
                                <div className="flex items-center justify-between gap-3 flex-wrap">
                                    <p className="text-xs font-bold uppercase tracking-[0.15em] text-emerald-700">Camion validé via XDock</p>
                                    <button
                                        type="button"
                                        data-testid="xdock-unlock-btn"
                                        onClick={unlockXdock}
                                        className="inline-flex items-center gap-1.5 text-xs font-bold text-emerald-800 hover:text-emerald-600 underline-offset-2 hover:underline"
                                        title="Déverrouiller pour modifier"
                                    >
                                        <RotateCcw className="h-3.5 w-3.5" />
                                        Modifier
                                    </button>
                                </div>
                                <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 font-heading font-black tracking-wider text-slate-900">
                                    <span className="inline-flex items-center gap-1.5 text-base sm:text-lg" data-testid="xdock-validated-tracteur">
                                        <Truck className="h-4 w-4 text-emerald-700" />
                                        {plate || '—'}
                                    </span>
                                    {remorque && (
                                        <span className="inline-flex items-center gap-1.5 text-sm sm:text-base text-slate-700" data-testid="xdock-validated-remorque">
                                            <Truck className="h-3.5 w-3.5 text-slate-400" />
                                            {remorque}
                                        </span>
                                    )}
                                    {(numeroEmSm || typeEmSm) && (
                                        <span className="inline-flex items-center gap-2 text-sm sm:text-base" data-testid="xdock-validated-tour">
                                            {typeEmSm && (
                                                <span className="rounded-full bg-emerald-100 text-emerald-800 px-2 py-0.5 text-[11px] font-bold tracking-wider">
                                                    {typeEmSm}
                                                </span>
                                            )}
                                            {numeroEmSm && (
                                                <span className="text-slate-700">Tournée n°{numeroEmSm}</span>
                                            )}
                                        </span>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-5" data-testid="new-folder-form">
                    {/* Plate block — visible uniquement en mode manuel (caché en pending/detecting/validated) */}
                    {xdockMode === 'manual' && (
                        <div className="rounded-lg border border-slate-200 bg-white p-4 sm:p-6">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">
                                Plaque tracteur *
                            </label>
                            <div className="mt-2 relative">
                                <Truck className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-400" />
                                <input
                                    data-testid="plate-input"
                                    value={plate}
                                    onChange={(e) => setPlate(cleanPlate(e.target.value))}
                                    placeholder="Ex : AB-123-CD, CT-49-AAA, M-AB 1234…"
                                    maxLength={PLATE_MAX_LEN}
                                    autoCapitalize="characters"
                                    autoCorrect="off"
                                    spellCheck="false"
                                    className="w-full h-14 rounded-md border border-slate-300 bg-white pl-12 pr-4 text-lg font-heading font-bold tracking-wider text-slate-900 placeholder:text-slate-300 placeholder:font-normal focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 transition uppercase"
                                />
                            </div>

                            <label className="mt-4 block text-xs font-bold uppercase tracking-wider text-slate-700">
                                Plaque remorque <span className="text-slate-400 font-normal normal-case">(optionnel)</span>
                            </label>
                            <div className="mt-2 relative">
                                <Truck className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-300" />
                                <input
                                    data-testid="remorque-input"
                                    value={remorque}
                                    onChange={(e) => setRemorque(cleanPlate(e.target.value))}
                                    placeholder="Plaque de la remorque"
                                    maxLength={PLATE_MAX_LEN}
                                    autoCapitalize="characters"
                                    autoCorrect="off"
                                    spellCheck="false"
                                    className="w-full h-12 rounded-md border border-slate-300 bg-white pl-12 pr-4 text-base font-heading font-bold tracking-wider text-slate-900 placeholder:text-slate-300 placeholder:font-normal focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 transition uppercase"
                                />
                            </div>
                        </div>
                    )}

                    {/* Phrases + Problem — toujours saisissables */}
                    {xdockMode !== 'pending' && xdockMode !== 'detecting' && (
                    <div className="rounded-lg border border-slate-200 bg-white p-4 sm:p-6">
                        <div className="flex items-center justify-between mb-3">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Phrases prédéfinies</label>
                            <span className="text-xs text-slate-400">Clique pour ajouter</span>
                        </div>
                        {phrases.length === 0 ? (
                            <p className="text-sm text-slate-400 italic">Aucune phrase configurée</p>
                        ) : (
                            <div className="flex flex-wrap gap-2" data-testid="phrases-list">
                                {phrases.map((p) => (
                                    <button
                                        type="button"
                                        key={p.id}
                                        data-testid={`phrase-${p.id}`}
                                        onClick={() => appendPhrase(p.text)}
                                        className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1.5 text-sm font-medium text-slate-700 hover:border-stef hover:bg-stef/5 hover:text-stef transition-all"
                                    >
                                        + {p.text}
                                    </button>
                                ))}
                            </div>
                        )}

                        <label className="mt-6 block text-xs font-bold uppercase tracking-wider text-slate-700">Description du problème *</label>
                        <textarea
                            data-testid="problem-textarea"
                            value={problem}
                            onChange={(e) => setProblem(e.target.value)}
                            rows={5}
                            placeholder="Décris le problème rencontré…"
                            className="mt-2 w-full rounded-md border border-slate-300 bg-white px-4 py-3 text-base text-slate-900 placeholder:text-slate-400 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 transition resize-y"
                        />
                    </div>
                    )}

                    {/* Photos */}
                    {xdockMode !== 'pending' && xdockMode !== 'detecting' && (
                    <div className="rounded-lg border border-slate-200 bg-white p-4 sm:p-6">
                        <div className="flex items-center justify-between mb-3">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">
                                Photos ({photos.length}/{MAX_PHOTOS})
                            </label>
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                            <input ref={cameraRef} type="file" accept="image/*" capture="environment" className="hidden" onChange={(e) => handleFiles(e.target.files)} data-testid="camera-input" />
                            <input ref={galleryRef} type="file" accept="image/*" multiple className="hidden" onChange={(e) => handleFiles(e.target.files)} data-testid="gallery-input" />
                            <button
                                type="button"
                                data-testid="open-camera-btn"
                                onClick={() => cameraRef.current?.click()}
                                disabled={photos.length >= MAX_PHOTOS}
                                className="h-12 rounded-md bg-stef text-white font-heading font-bold flex items-center justify-center gap-2 hover:bg-stef-hover transition-all disabled:opacity-50"
                            >
                                <Camera className="h-4 w-4" /> Prendre
                            </button>
                            <button
                                type="button"
                                data-testid="open-gallery-btn"
                                onClick={() => galleryRef.current?.click()}
                                disabled={photos.length >= MAX_PHOTOS}
                                className="h-12 rounded-md border border-slate-300 bg-white text-slate-700 font-heading font-bold flex items-center justify-center gap-2 hover:border-stef hover:text-stef transition-all disabled:opacity-50"
                            >
                                <ImagePlus className="h-4 w-4" /> Galerie
                            </button>
                        </div>

                        {photos.length > 0 ? (
                            <div className="mt-4 grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2" data-testid="photos-grid">
                                {photos.map((src, i) => (
                                    <div key={i} className="relative group aspect-square rounded-md overflow-hidden border border-slate-200">
                                        <img src={src} alt="" className="h-full w-full object-cover" />
                                        <button
                                            type="button"
                                            data-testid={`remove-photo-${i}`}
                                            onClick={() => removePhoto(i)}
                                            className="absolute top-1 right-1 h-6 w-6 rounded-full bg-black/70 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition"
                                        >
                                            <X className="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className="mt-4 rounded-md border-2 border-dashed border-slate-200 bg-slate-50 p-8 text-center">
                                <Camera className="mx-auto h-8 w-8 text-slate-300" />
                                <p className="mt-2 font-heading font-bold text-slate-600">Aucune photo ajoutée</p>
                                <p className="text-xs text-slate-400">0 à {MAX_PHOTOS} photos (optionnel)</p>
                            </div>
                        )}
                    </div>
                    )}

                    {/* Submit bar */}
                    {xdockMode !== 'pending' && xdockMode !== 'detecting' && (
                    <div className="sticky bottom-0 sm:static -mx-4 sm:mx-0 px-4 sm:px-0 pt-3 pb-4 sm:pb-0 bg-gradient-to-t from-white via-white to-white/0 sm:bg-none flex flex-col sm:flex-row gap-3">
                        <button
                            type="button"
                            data-testid="cancel-btn"
                            onClick={() => navigate('/')}
                            className="sm:order-1 h-12 rounded-md border border-slate-300 bg-white text-slate-700 font-semibold hover:bg-slate-50 transition-all px-6"
                        >
                            Annuler
                        </button>
                        <button
                            type="submit"
                            data-testid="submit-folder-btn"
                            disabled={submitting}
                            className="sm:order-2 sm:flex-1 h-14 rounded-md bg-stef text-white font-heading font-bold tracking-wide hover:bg-stef-hover transition-all flex items-center justify-center gap-2 disabled:opacity-60 shadow-sm"
                        >
                            <FolderPlus className="h-5 w-5" />
                            {submitting ? 'Création…' : 'Créer le dossier'}
                        </button>
                    </div>
                    )}
                </form>
            </div>
        </Layout>
    );
}
