import { useEffect, useState } from 'react';

interface DossierDetail {
    famille: 'dossiers';
    numero: string;
    nom: string;
    prenom: string;
    raison_sociale: string | null;
    adresse: string | null;
    code_postal: string | null;
    ville: string | null;
    telephone_fixe: string | null;
    telephone_mobile: string | null;
    courriel: string | null;
    travaux_realises: boolean;
    nb_eh: number | null;
    nom_installateur: string | null;
    dispositif: string | null;
    is_pro: boolean;
}

interface AnnuaireDetail {
    famille: 'annuaire';
    typologie: string;
    nom: string;
    prenom: string;
    raison_sociale: string | null;
    adresse: string | null;
    code_postal: string | null;
    ville: string | null;
    telephone_fixe: string | null;
    telephone_mobile: string | null;
    courriel: string | null;
}

interface SpancsDetail {
    famille: 'spancs';
    typologie: 'SPANCS';
    nom: string;
    prenom: string;
    raison_sociale: string | null;
    adresse: string | null;
    code_postal: string | null;
    ville: string | null;
    telephone_fixe: string | null;
    telephone_mobile: string | null;
    courriel: string | null;
}

interface DepanneurDetail {
    famille: 'depanneurs';
    typologie: 'Dépanneurs';
    nom: string;
    prenom: string;
    raison_sociale: string | null;
    adresse: string | null;
    code_postal: string | null;
    ville: string | null;
    telephone_fixe: string | null;
    telephone_mobile: string | null;
    courriel: string | null;
}

export type FeatureDetail = DossierDetail | AnnuaireDetail | SpancsDetail | DepanneurDetail;

interface Props {
    id: number;
    famille: 'dossiers' | 'annuaire' | 'spancs' | 'depanneurs';
    type: string;
    onClose: () => void;
}

const TYPE_COLOR: Record<string, string> = {
    'Chantiers':     'bg-[#2d7a70]',
    'Projets':       'bg-[#5aacaa]',
    'Autres':        'bg-[#7a9290]',
    'IR':            'bg-[#4a90d9]',
    'TP':            'bg-[#1a6fb5]',
    'Fournisseurs':  'bg-[#e8943a]',
    'Prescripteurs': 'bg-[#9b59b6]',
    'SPANCS':        'bg-[#27ae60]',
    'Dépanneurs':    'bg-[#e74c3c]',
};

// ─── Sous-composants ──────────────────────────────────────────────────────────

function PhoneRow({ tel }: { tel: string }) {
    return (
        <a
            href={`tel:${tel.replace(/\s/g, '')}`}
            className="flex items-center gap-2.5 text-sm text-[#117176] hover:text-[#0c4f54] transition-colors"
        >
            <svg className="w-4 h-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z" />
            </svg>
            <span>{tel}</span>
        </a>
    );
}

function EmailRow({ email }: { email: string }) {
    return (
        <a
            href={`mailto:${email}`}
            className="flex items-center gap-2.5 text-sm text-[#117176] hover:text-[#0c4f54] transition-colors"
        >
            <svg className="w-4 h-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75" />
            </svg>
            <span className="truncate max-w-[220px]">{email}</span>
        </a>
    );
}

function AddressBlock({ adresse, codePostal, ville }: { adresse?: string | null; codePostal?: string | null; ville?: string | null }) {
    const line2 = [codePostal, ville].filter(Boolean).join(' ');
    if (!adresse && !line2) return null;
    return (
        <div className="flex items-start gap-2.5 text-sm text-gray-600">
            <svg className="w-4 h-4 shrink-0 text-gray-400 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1 1 15 0Z" />
            </svg>
            <div className="leading-snug">
                {adresse && <div>{adresse}</div>}
                {line2   && <div>{line2}</div>}
            </div>
        </div>
    );
}

// ─── Corps dossier ────────────────────────────────────────────────────────────

function DossierBody({ detail }: { detail: DossierDetail }) {
    const fullName   = [detail.prenom, detail.nom?.toUpperCase()].filter(Boolean).join(' ');
    const showTech   = detail.travaux_realises || !!detail.dispositif;

    return (
        <div className="flex flex-col gap-3">
            {detail.is_pro && detail.raison_sociale && (
                <p className="text-base font-bold text-gray-900 leading-tight">{detail.raison_sociale}</p>
            )}
            {fullName && (
                <p className="text-sm font-semibold text-gray-700">{fullName}</p>
            )}

            <AddressBlock adresse={detail.adresse} codePostal={detail.code_postal} ville={detail.ville} />

            {(detail.telephone_fixe || detail.telephone_mobile) && (
                <div className="flex flex-col gap-1.5">
                    {detail.telephone_fixe   && <PhoneRow tel={detail.telephone_fixe} />}
                    {detail.telephone_mobile && <PhoneRow tel={detail.telephone_mobile} />}
                </div>
            )}
            {detail.courriel && <EmailRow email={detail.courriel} />}

            {showTech && (
                <div className="pt-3 mt-1 border-t border-gray-100 flex flex-col gap-1.5">
                    {detail.dispositif && (
                        <div className="text-xs text-gray-600">
                            <span className="font-medium text-gray-500">Dispositif  </span>{detail.dispositif}
                        </div>
                    )}
                    {detail.nb_eh != null && detail.nb_eh > 0 && (
                        <div className="text-xs text-gray-600">
                            <span className="font-medium text-gray-500">Capacité  </span>{detail.nb_eh} EH
                        </div>
                    )}
                    {detail.nom_installateur && (
                        <div className="text-xs text-gray-600">
                            <span className="font-medium text-gray-500">Réalisé par  </span>{detail.nom_installateur}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

// ─── Corps annuaire ───────────────────────────────────────────────────────────

function AnnuaireBody({ detail }: { detail: AnnuaireDetail }) {
    const fullName = [detail.prenom, detail.nom?.toUpperCase()].filter(Boolean).join(' ');

    return (
        <div className="flex flex-col gap-3">
            {detail.raison_sociale && (
                <p className="text-base font-bold text-gray-900 leading-tight">{detail.raison_sociale}</p>
            )}
            {fullName && (
                <p className="text-sm font-semibold text-gray-700">{fullName}</p>
            )}

            <AddressBlock adresse={detail.adresse} codePostal={detail.code_postal} ville={detail.ville} />

            {(detail.telephone_fixe || detail.telephone_mobile) && (
                <div className="flex flex-col gap-1.5">
                    {detail.telephone_fixe   && <PhoneRow tel={detail.telephone_fixe} />}
                    {detail.telephone_mobile && <PhoneRow tel={detail.telephone_mobile} />}
                </div>
            )}
            {detail.courriel && <EmailRow email={detail.courriel} />}
        </div>
    );
}

// ─── Corps SPANCS / Dépanneurs (même structure qu'annuaire) ──────────────────

function ContactBody({ detail }: { detail: SpancsDetail | DepanneurDetail }) {
    const fullName = [detail.prenom, detail.nom?.toUpperCase()].filter(Boolean).join(' ');

    return (
        <div className="flex flex-col gap-3">
            {detail.raison_sociale && (
                <p className="text-base font-bold text-gray-900 leading-tight">{detail.raison_sociale}</p>
            )}
            {fullName && (
                <p className="text-sm font-semibold text-gray-700">{fullName}</p>
            )}

            <AddressBlock adresse={detail.adresse} codePostal={detail.code_postal} ville={detail.ville} />

            {(detail.telephone_fixe || detail.telephone_mobile) && (
                <div className="flex flex-col gap-1.5">
                    {detail.telephone_fixe   && <PhoneRow tel={detail.telephone_fixe} />}
                    {detail.telephone_mobile && <PhoneRow tel={detail.telephone_mobile} />}
                </div>
            )}
            {detail.courriel && <EmailRow email={detail.courriel} />}
        </div>
    );
}

// ─── Composant principal ──────────────────────────────────────────────────────

export default function FeaturePopup({ id, famille, type, onClose }: Props) {
    const [detail,  setDetail]  = useState<FeatureDetail | null>(null);
    const [error,   setError]   = useState(false);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        setDetail(null);
        setError(false);
        // Légère pause pour déclencher l'animation d'entrée
        const t = setTimeout(() => setVisible(true), 10);
        const qs = new URLSearchParams({ id: String(id), famille });
        fetch(`/api/carte/detail?${qs}`)
            .then(r => r.ok ? r.json() : Promise.reject())
            .then((d: FeatureDetail) => setDetail(d))
            .catch(() => setError(true));
        return () => clearTimeout(t);
    }, [id, famille]);

    const badgeColor = TYPE_COLOR[type] ?? 'bg-gray-500';

    return (
        /* Overlay */
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">

            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-black/50 cursor-pointer"
                onClick={onClose}
            />

            {/* Boîte de dialogue */}
            <div
                className={[
                    'relative z-10 bg-white rounded-2xl shadow-lg',
                    'w-full max-w-sm flex flex-col overflow-hidden',
                    'transition-transform duration-150 ease-out',
                    visible ? 'translate-y-0' : 'translate-y-4',
                ].join(' ')}
            >
                {/* Header */}
                <div className="flex items-center gap-3 px-6 py-5 border-b border-gray-100 shrink-0">
                    <span className={`inline-flex items-center h-5 px-2 rounded-md text-[11px] font-bold text-white ${badgeColor}`}>
                        {type}
                    </span>
                    <div className="flex-1 min-w-0" />
                    <button
                        onClick={onClose}
                        className="w-8 h-8 flex items-center justify-center rounded-md text-gray-400 hover:bg-gray-100 hover:text-gray-700 transition-colors"
                        aria-label="Fermer"
                    >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                {/* Body */}
                <div className="flex-1 overflow-y-auto px-6 py-5">
                    {!detail && !error && (
                        <div className="flex items-center gap-2 text-gray-400 text-sm py-2">
                            <div className="w-4 h-4 border-2 border-gray-300 border-t-[#117176] rounded-full animate-spin" />
                            Chargement…
                        </div>
                    )}

                    {error && (
                        <p className="text-red-500 text-sm py-2">Impossible de charger les détails.</p>
                    )}

                    {detail?.famille === 'dossiers'   && <DossierBody  detail={detail} />}
                    {detail?.famille === 'annuaire'   && <AnnuaireBody detail={detail} />}
                    {detail?.famille === 'spancs'     && <ContactBody  detail={detail} />}
                    {detail?.famille === 'depanneurs' && <ContactBody  detail={detail} />}
                </div>
            </div>
        </div>
    );
}
