import { CalendarDays, Filter, Loader2, Mail, MessageCircle, MessageCircleQuestion, RefreshCw, X } from 'lucide-react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { apiFetch } from '@/lib/loading/api-fetch';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Discussion } from './types';

const TLL_LOGO = '/creatorsLogo/thelandlord.png';
const AIRBNB_LOGO = '/creatorsLogo/airbnb.png';
const BOOKING_LOGO = '/creatorsLogo/booking.png';
const EXPEDIA_LOGO = '/creatorsLogo/expedia.webp';
const FACEBOOK_LOGO = '/facebook.png';
const INSTAGRAM_LOGO = '/instagram.png';

interface FranchiseOption {
    id: number;
    name: string;
}

interface Props {
    discussions: Discussion[];
    activeDiscussionId: number | string | null;
    setActiveDiscussion: (d: Discussion) => void;
    searchTerm: string;
    setSearchTerm: (term: string) => void;
    searchResults?: Discussion[] | null;
    onLoadMore?: () => void;
    loadingMore?: boolean;
    hasMore?: boolean;
    franchises?: FranchiseOption[];
    currentFranchiseId?: number | null;
    onFranchiseChange?: (id: number) => void;
}

// Filter chips: key → channels it matches
const FILTER_CHIPS: { key: string; label: string; logo?: string; logoBg?: string; channels: string[] }[] = [
    { key: 'all',       label: 'Tout',        channels: [] },
    { key: 'tll',       label: 'TLL',         logo: TLL_LOGO, logoBg: 'bg-[#2c3e50]', channels: ['tll_internal'] },
    { key: 'airbnb',    label: 'Airbnb',      logo: AIRBNB_LOGO, channels: ['Airbnb'] },
    { key: 'booking',   label: 'Booking',     logo: BOOKING_LOGO, channels: ['BookingCom'] },
    { key: 'facebook',  label: 'Facebook',    logo: FACEBOOK_LOGO, channels: ['facebook_comment', 'facebook_message'] },
    { key: 'instagram', label: 'Instagram',   logo: INSTAGRAM_LOGO, channels: ['instagram_comment', 'instagram_message'] },
];

const CHANNEL_COLORS: Record<string, string> = {
    facebook_comment:   'text-blue-600',
    facebook_message:   'text-blue-700',
    instagram_comment:  'text-pink-500',
    instagram_message:  'text-pink-600',
    tll_internal:       'text-green-600',
    Airbnb:             'text-red-500',
    BookingCom:         'text-blue-500',
};

const CHANNEL_LOGOS: Record<string, { src: string; alt: string; bg?: string }> = {
    tll_internal:      { src: TLL_LOGO, alt: 'The Landlord', bg: 'bg-[#2c3e50]' },
    Airbnb:            { src: AIRBNB_LOGO, alt: 'Airbnb' },
    BookingCom:        { src: BOOKING_LOGO, alt: 'Booking.com' },
    Expedia:           { src: EXPEDIA_LOGO, alt: 'Expedia' },
    facebook_comment:  { src: FACEBOOK_LOGO, alt: 'Facebook' },
    facebook_message:  { src: FACEBOOK_LOGO, alt: 'Facebook' },
    instagram_comment: { src: INSTAGRAM_LOGO, alt: 'Instagram' },
    instagram_message: { src: INSTAGRAM_LOGO, alt: 'Instagram' },
};

const ChannelIcon = ({ channel }: { channel?: string | null }) => {
    const logo = CHANNEL_LOGOS[channel ?? ''];
    if (logo) {
        return <img src={logo.src} alt={logo.alt} className={`h-9 w-9 rounded-full object-contain ${logo.bg ? logo.bg + ' p-1' : ''}`} />;
    }
    const cls = `h-8 w-8 ${CHANNEL_COLORS[channel ?? ''] ?? 'text-secondary'}`;
    switch (channel) {
        case 'Email':
            return <Mail className={cls} />;
        case 'Readonly':
            return <MessageCircle className={cls} />;
        default:
            return <MessageCircleQuestion className={cls} />;
    }
};

const TZ = 'Africa/Tunis';

const isToday = (d?: string | null) => {
    if (!d) return false;
    const opts: Intl.DateTimeFormatOptions = { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' };
    return new Intl.DateTimeFormat('fr-FR', opts).format(new Date(d)) ===
           new Intl.DateTimeFormat('fr-FR', opts).format(new Date());
};

const formatDate = (d?: string | null) => {
    if (!d) return '--';
    return new Date(d).toLocaleDateString('fr-FR', { timeZone: TZ, day: '2-digit', month: 'short', year: 'numeric' });
};

const formatTime = (d?: string | null) => {
    if (!d) return '';
    return new Date(d).toLocaleTimeString('fr-FR', { timeZone: TZ, hour: '2-digit', minute: '2-digit' });
};

const DiscussionsList: React.FC<Props> = ({ discussions, activeDiscussionId, setActiveDiscussion, searchTerm, setSearchTerm, searchResults, onLoadMore, loadingMore, hasMore, franchises, currentFranchiseId, onFranchiseChange }) => {
    const scrollRef = useRef<HTMLDivElement>(null);
    const popoverRef = useRef<HTMLDivElement>(null);
    const [activeFilter, setActiveFilter] = useState('all');
    const [showFilter, setShowFilter] = useState(false);

    // ── Bulk sync state ─────────────────────────────────────────────────
    const [syncRunning, setSyncRunning] = useState(false);
    const [syncOpen, setSyncOpen] = useState(false);
    const [syncDate, setSyncDate] = useState<Date | undefined>(undefined);
    const [syncBusy, setSyncBusy] = useState(false);
    const [confirmAllOpen, setConfirmAllOpen] = useState(false);

    const fetchSyncStatus = useCallback(async () => {
        try {
            const res = await fetch('/guest-communication/bulk-sync/status');
            const data = await res.json();
            setSyncRunning(!!data?.running);
        } catch {
            // silent
        }
    }, []);

    useEffect(() => {
        fetchSyncStatus();
        const id = window.setInterval(fetchSyncStatus, 5000);
        return () => window.clearInterval(id);
    }, [fetchSyncStatus]);

    const launchBulkSync = async (fromDate: string | null) => {
        if (syncBusy || syncRunning) return;
        setSyncBusy(true);
        try {
            const res = await apiFetch('/guest-communication/bulk-sync', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
                },
                body: JSON.stringify({ from_date: fromDate }),
            });
            const data = await res.json().catch(() => null);
            if (res.status === 409) {
                toast.error('Une synchronisation est déjà en cours');
                setSyncRunning(true);
                return;
            }
            if (!res.ok) {
                toast.error(data?.error ?? 'Échec du lancement');
                return;
            }
            toast.success(`Sync lancée à partir de ${data?.from_date ?? '2025-01-01'}`);
            setSyncRunning(true);
            setSyncOpen(false);
            setConfirmAllOpen(false);
            setSyncDate(undefined);
        } catch {
            toast.error('Erreur réseau');
        } finally {
            setSyncBusy(false);
        }
    };

    const formatDateForApi = (d: Date) => {
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${y}-${m}-${day}`;
    };

    // Close popover on outside click
    useEffect(() => {
        if (!showFilter) return;
        const handler = (e: MouseEvent) => {
            if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
                setShowFilter(false);
            }
        };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [showFilter]);

    const handleScroll = useCallback(() => {
        const el = scrollRef.current;
        if (!el || !onLoadMore || loadingMore || !hasMore) return;
        if (el.scrollTop + el.clientHeight >= el.scrollHeight - 100) {
            onLoadMore();
        }
    }, [onLoadMore, loadingMore, hasMore]);

    const activeChip = FILTER_CHIPS.find((c) => c.key === activeFilter);
    const allowedChannels = activeChip?.channels ?? [];

    // Use server-side search results when available, otherwise filter client-side
    const baseList = searchResults ?? discussions;
    const filtered = baseList.filter((d) => {
        if (!searchResults) {
            const matchesSearch =
                (d.recipient_name || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                (d.property_name || '').toLowerCase().includes(searchTerm.toLowerCase());
            if (!matchesSearch) return false;
        }
        const matchesFilter = allowedChannels.length === 0 || allowedChannels.includes(d.communication_channel ?? '');
        return matchesFilter;
    });

    // Auto-load more when filter is active but not enough results
    useEffect(() => {
        if (activeFilter !== 'all' && filtered.length < 5 && hasMore && !loadingMore && onLoadMore) {
            onLoadMore();
        }
    }, [activeFilter, filtered.length, hasMore, loadingMore]);

    const today  = filtered.filter((d) => isToday(d.last_message_date));
    const older  = filtered.filter((d) => !isToday(d.last_message_date));

    const renderCard = (d: Discussion) => {
        const isActive = activeDiscussionId === d.id;
        const hasUnread = (d.unread_messages ?? 0) > 0;

        return (
            <div
                key={`${d.communication_channel}-${d.id}`}
                className={`relative mb-2 w-full cursor-pointer rounded-xl border p-3 transition-all max-[978px]:my-auto max-[978px]:min-w-[280px] ${
                    isActive
                        ? 'border-[#31b08f] bg-[#f0faf7] shadow-md'
                        : 'border-transparent bg-white shadow-sm hover:shadow-md hover:border-gray-200'
                }`}
                onClick={() => setActiveDiscussion(d)}
            >
                <div className="flex w-full items-center gap-3">
                    <div className="flex-shrink-0">
                        <ChannelIcon channel={d.communication_channel} />
                    </div>
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between gap-2">
                            <h3 className={`truncate text-sm font-semibold ${hasUnread ? 'text-gray-900' : 'text-gray-700'}`}>
                                {d.recipient_name || 'Client'}
                            </h3>
                            <span className="flex-shrink-0 text-xs text-gray-400">
                                {isToday(d.last_message_date) ? formatTime(d.last_message_date) : formatDate(d.last_message_date)}
                            </span>
                        </div>
                        {d.property_name && (
                            <p className="truncate text-xs text-gray-500">{d.property_name}</p>
                        )}
                        <div className="mt-1 flex items-center justify-between gap-2">
                            <p className={`truncate text-xs ${hasUnread ? 'font-medium text-gray-700' : 'text-gray-400'}`}>
                                {d.preview ? d.preview.replace(/<[^>]*>/g, '') : ''}
                            </p>
                            {hasUnread && (
                                <span className="bg-[#31b08f] flex-shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-bold text-white">
                                    {d.unread_messages}
                                </span>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        );
    };

    return (
        <div
            id="discussions-container"
            className="flex w-[300px] flex-shrink-0 flex-col rounded-xl bg-[#F7F7F7] overflow-hidden max-[978px]:w-full"
        >
            <div className="flex-shrink-0 p-4 pb-2">
                {franchises && franchises.length > 0 && onFranchiseChange && (
                    <div className="mb-3">
                        <label className="mb-1 block text-[11px] font-semibold uppercase tracking-wide text-gray-500">
                            Franchise
                        </label>
                        <select
                            value={currentFranchiseId ?? ''}
                            onChange={(e) => onFranchiseChange(Number(e.target.value))}
                            className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm focus:border-[#31b08f] focus:outline-none"
                        >
                            {franchises.map((f) => (
                                <option key={f.id} value={f.id}>
                                    {f.name}
                                </option>
                            ))}
                        </select>
                    </div>
                )}
                <div className="flex items-center justify-between mb-3">
                    <h2 className="text-primary text-xl font-bold">Discussions</h2>
                    <div className="flex items-center gap-2">
                    <Popover open={syncOpen} onOpenChange={setSyncOpen}>
                        <PopoverTrigger asChild>
                            <button
                                disabled={syncBusy}
                                className={`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-all ${
                                    syncRunning
                                        ? 'bg-amber-100 text-amber-700 border border-amber-200 cursor-default'
                                        : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50'
                                } disabled:opacity-50`}
                                title={syncRunning ? 'Sync en cours' : 'Synchroniser RentalsUnited'}
                            >
                                {syncRunning ? (
                                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                ) : (
                                    <RefreshCw className="h-3.5 w-3.5" />
                                )}
                                {syncRunning && <span>En cours…</span>}
                            </button>
                        </PopoverTrigger>
                        <PopoverContent align="end" className="w-auto p-3 space-y-2">
                            <div className="flex items-center gap-2 text-xs font-semibold text-gray-700">
                                <CalendarDays className="h-3.5 w-3.5" />
                                Synchroniser depuis…
                            </div>
                            <Calendar
                                mode="single"
                                selected={syncDate}
                                onSelect={setSyncDate}
                                disabled={syncRunning}
                                toDate={new Date()}
                                initialFocus
                            />
                            <button
                                onClick={() => syncDate && launchBulkSync(formatDateForApi(syncDate))}
                                disabled={!syncDate || syncRunning || syncBusy}
                                className="w-full rounded-lg bg-[#31b08f] px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-[#279174] disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                Sync depuis cette date
                            </button>
                            <div className="border-t border-gray-100" />
                            <button
                                onClick={() => { setSyncOpen(false); setConfirmAllOpen(true); }}
                                disabled={syncRunning || syncBusy}
                                className="w-full rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                Sync tout (depuis 2025-01-01)
                            </button>
                        </PopoverContent>
                    </Popover>

                    <AlertDialog open={confirmAllOpen} onOpenChange={setConfirmAllOpen}>
                        <AlertDialogContent>
                            <AlertDialogHeader>
                                <AlertDialogTitle>Sync complète depuis 2025-01-01 ?</AlertDialogTitle>
                                <AlertDialogDescription>
                                    Cette opération parcourt tous les mois depuis 2025-01-01 via l'API RentalsUnited.
                                    Elle peut prendre plusieurs minutes à plusieurs heures et hit l'API RU intensivement.
                                    Le job tourne en arrière-plan, tu peux fermer la page.
                                </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                                <AlertDialogCancel>Annuler</AlertDialogCancel>
                                <AlertDialogAction onClick={() => launchBulkSync(null)} disabled={syncBusy}>
                                    Lancer
                                </AlertDialogAction>
                            </AlertDialogFooter>
                        </AlertDialogContent>
                    </AlertDialog>

                    <div className="relative" ref={popoverRef}>
                        <button
                            onClick={() => setShowFilter(!showFilter)}
                            className={`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-all ${
                                activeFilter !== 'all'
                                    ? 'bg-[#31b08f] text-white shadow-sm'
                                    : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50'
                            }`}
                        >
                            <Filter className="h-3.5 w-3.5" />
                            {activeFilter !== 'all' && (
                                <span>{FILTER_CHIPS.find((c) => c.key === activeFilter)?.label}</span>
                            )}
                        </button>

                        {/* Popover */}
                        <div
                            className={`absolute right-0 top-full z-50 mt-2 w-48 origin-top-right rounded-xl bg-white p-2 shadow-lg ring-1 ring-black/5 transition-all duration-200 ${
                                showFilter
                                    ? 'scale-100 opacity-100'
                                    : 'pointer-events-none scale-95 opacity-0'
                            }`}
                        >
                            {FILTER_CHIPS.map((chip) => {
                                const active = activeFilter === chip.key;
                                return (
                                    <button
                                        key={chip.key}
                                        onClick={() => { setActiveFilter(chip.key); setShowFilter(false); }}
                                        className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] transition-colors ${
                                            active
                                                ? 'bg-[#f0faf7] font-semibold text-[#31b08f]'
                                                : 'text-gray-700 hover:bg-gray-50'
                                        }`}
                                    >
                                        {chip.logo ? (
                                            <img
                                                src={chip.logo}
                                                alt={chip.label}
                                                className={`h-5 w-5 rounded-full object-contain ${chip.logoBg ? chip.logoBg + ' p-0.5' : ''}`}
                                            />
                                        ) : (
                                            <div className="flex h-5 w-5 items-center justify-center rounded-full bg-gray-100">
                                                <Filter className="h-3 w-3 text-gray-400" />
                                            </div>
                                        )}
                                        <span className="flex-1 text-left">{chip.label}</span>
                                        {active && <div className="h-1.5 w-1.5 rounded-full bg-[#31b08f]" />}
                                    </button>
                                );
                            })}
                            {activeFilter !== 'all' && (
                                <>
                                    <div className="mx-2 my-1 border-t border-gray-100" />
                                    <button
                                        onClick={() => { setActiveFilter('all'); setShowFilter(false); }}
                                        className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-red-500 hover:bg-red-50"
                                    >
                                        <X className="h-4 w-4" />
                                        <span>Retirer le filtre</span>
                                    </button>
                                </>
                            )}
                        </div>
                    </div>
                    </div>
                </div>
                <input
                    className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm placeholder:text-slate-400 focus:border-[#31b08f] focus:outline-none"
                    placeholder="Rechercher..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                />
            </div>

            <div ref={scrollRef} onScroll={handleScroll} className="flex-1 overflow-y-auto px-3 pb-3">
                {today.length > 0 && (
                    <>
                        <div className="text-secondary my-2 hidden text-center text-xs font-semibold uppercase tracking-wide md:block">
                            Aujourd'hui
                        </div>
                        {today.map(renderCard)}
                    </>
                )}
                {older.length > 0 && (
                    <>
                        {today.length > 0 && (
                            <div className="text-secondary my-2 text-center text-xs font-semibold uppercase tracking-wide max-[978px]:hidden">
                                Plus anciens
                            </div>
                        )}
                        {older.map(renderCard)}
                    </>
                )}
                {filtered.length === 0 && <div className="mt-8 text-center text-sm text-gray-400">Aucune discussion trouvée</div>}
                {loadingMore && (
                    <div className="flex justify-center py-3">
                        <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                    </div>
                )}
            </div>

        </div>
    );
};

export default DiscussionsList;
