/**
 * TaxiBook Partner - Dashboard View
 * ==================================
 * Vue d'ensemble du portail Partenaire.
 *  - Liste des outils disponibles (Smart, Agent, IVR, Tablet, ...)
 *  - Stats des réservations par jour, par source et par agent.
 */

const SOURCE_LABELS = {
    partner_app: 'App Partenaire',
    minisite: 'Mini-site',
    site: 'Site web',
    smart: 'Smart',
    agent: 'Agent',
    tablet: 'Tablet',
    ivr: 'IVR',
    gateway: 'Gateway (API)',
    manager: 'Manager',
    app_client: 'App Client',
    app_my: 'App MY',
    partner: 'Partenaire',
    unknown: 'Autre'
};

const SOURCE_COLORS = {
    partner_app: '#8b5cf6',
    minisite: '#10b981',
    site: '#0ea5e9',
    smart: '#22c55e',
    agent: '#3b82f6',
    tablet: '#6366f1',
    ivr: '#f43f5e',
    gateway: '#0f172a',
    manager: '#f59e0b',
    app_client: '#06b6d4',
    app_my: '#14b8a6',
    partner: '#a855f7',
    unknown: '#94a3b8'
};

const TOOL_COLOR_CLASSES = {
    amber: { bg: 'bg-amber-50', text: 'text-amber-600', icon: 'bg-amber-100 text-amber-600', ring: 'ring-amber-200' },
    emerald: { bg: 'bg-emerald-50', text: 'text-emerald-600', icon: 'bg-emerald-100 text-emerald-600', ring: 'ring-emerald-200' },
    blue: { bg: 'bg-blue-50', text: 'text-blue-600', icon: 'bg-blue-100 text-blue-600', ring: 'ring-blue-200' },
    indigo: { bg: 'bg-indigo-50', text: 'text-indigo-600', icon: 'bg-indigo-100 text-indigo-600', ring: 'ring-indigo-200' },
    sky: { bg: 'bg-sky-50', text: 'text-sky-600', icon: 'bg-sky-100 text-sky-600', ring: 'ring-sky-200' },
    purple: { bg: 'bg-purple-50', text: 'text-purple-600', icon: 'bg-purple-100 text-purple-600', ring: 'ring-purple-200' },
    rose: { bg: 'bg-rose-50', text: 'text-rose-600', icon: 'bg-rose-100 text-rose-600', ring: 'ring-rose-200' },
    teal: { bg: 'bg-teal-50', text: 'text-teal-600', icon: 'bg-teal-100 text-teal-600', ring: 'ring-teal-200' },
    orange: { bg: 'bg-orange-50', text: 'text-orange-600', icon: 'bg-orange-100 text-orange-600', ring: 'ring-orange-200' },
    slate: { bg: 'bg-slate-50', text: 'text-slate-700', icon: 'bg-slate-200 text-slate-800', ring: 'ring-slate-300' }
};

const sourceLabel = (s) => SOURCE_LABELS[s] || (s || 'Autre');
const sourceColor = (s) => SOURCE_COLORS[s] || SOURCE_COLORS.unknown;
const fmtNumber = (n) => (n || 0).toLocaleString('fr-CH');
const fmtMoney = (n) => `${(parseFloat(n) || 0).toLocaleString('fr-CH', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} CHF`;

// ============================================================================
// STAT CARD
// ============================================================================

const DashStatCard = ({ icon, label, value, sublabel, color = 'primary' }) => (
    <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
        <div className="flex items-start justify-between mb-3">
            <div className={`w-12 h-12 bg-${color}-100 text-${color}-600 rounded-xl flex items-center justify-center`}>
                <i className={`fas ${icon} text-xl`}></i>
            </div>
        </div>
        <p className="text-3xl font-bold text-dark-900 mb-1">{value}</p>
        <p className="text-dark-500 text-sm font-medium">{label}</p>
        {sublabel && <p className="text-dark-400 text-xs mt-1">{sublabel}</p>}
    </div>
);

// ============================================================================
// TOOL CARD
// ============================================================================

const ToolCard = ({ tool }) => {
    const c = TOOL_COLOR_CLASSES[tool.color] || TOOL_COLOR_CLASSES.amber;
    const enabled = tool.enabled !== false;
    return (
        <div className={`relative rounded-2xl border ${enabled ? 'border-dark-100 bg-white' : 'border-dark-100 bg-dark-50 opacity-70'} p-5 shadow-sm flex flex-col`}>
            <div className="flex items-start gap-4 mb-3">
                <div className={`w-12 h-12 ${c.icon} rounded-xl flex items-center justify-center flex-shrink-0`}>
                    <i className={`fas ${tool.icon} text-xl`}></i>
                </div>
                <div className="min-w-0">
                    <h3 className="text-lg font-bold text-dark-900 truncate">{tool.name}</h3>
                    <p className="text-sm text-dark-500 leading-snug">{tool.description}</p>
                </div>
            </div>
            <div className="mt-auto pt-3 flex items-center justify-between gap-2">
                <div className="flex items-center gap-2 flex-wrap">
                    {enabled ? (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-700">
                            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                            Actif
                        </span>
                    ) : (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-dark-200 text-dark-600">
                            Indisponible
                        </span>
                    )}
                    {typeof tool.accounts_count === 'number' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-dark-100 text-dark-700">
                            <i className="fas fa-user text-[10px]"></i>
                            {tool.accounts_count} compte{tool.accounts_count > 1 ? 's' : ''}
                        </span>
                    )}
                    {typeof tool.count === 'number' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-dark-100 text-dark-700">
                            {tool.count}
                        </span>
                    )}
                    {tool.accounts === 'main' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                            <i className="fas fa-crown text-[10px]"></i>
                            Compte principal
                        </span>
                    )}
                </div>
                {enabled && tool.url && (
                    <a
                        href={tool.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm font-semibold text-primary-600 hover:text-primary-700 inline-flex items-center gap-1.5"
                    >
                        Ouvrir
                        <i className="fas fa-arrow-up-right-from-square text-xs"></i>
                    </a>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// STACKED BAR CHART (par jour, par source)
// ============================================================================

const DailyChart = ({ dayList, perDay, sources }) => {
    const map = {};
    dayList.forEach(d => { map[d] = { day: d, total: 0, sources: {} }; });
    perDay.forEach(row => {
        if (!map[row.day]) map[row.day] = { day: row.day, total: 0, sources: {} };
        map[row.day].sources[row.source] = (map[row.day].sources[row.source] || 0) + (row.total || 0);
        map[row.day].total += (row.total || 0);
    });
    const days = dayList.map(d => map[d]);
    const max = Math.max(1, ...days.map(d => d.total));

    const sourceKeys = Array.from(new Set(perDay.map(r => r.source))).sort();
    if (sourceKeys.length === 0) sourceKeys.push('unknown');

    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-4">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Réservations par jour</h3>
                    <p className="text-sm text-dark-500">Empilées par source</p>
                </div>
            </div>

            {/* Légende */}
            <div className="flex flex-wrap gap-3 mb-5">
                {sourceKeys.map(s => (
                    <div key={s} className="flex items-center gap-1.5 text-xs text-dark-600">
                        <span className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: sourceColor(s) }}></span>
                        {sourceLabel(s)}
                    </div>
                ))}
            </div>

            {/* Graphique */}
            <div className="flex items-end gap-1 h-48 overflow-x-auto pb-1">
                {days.map((d, idx) => {
                    const totalH = max > 0 ? Math.max(2, (d.total / max) * 100) : 2;
                    const dt = new Date(d.day + 'T00:00:00');
                    const showLabel = idx % Math.ceil(days.length / 10) === 0 || idx === days.length - 1;
                    return (
                        <div key={d.day} className="flex-1 min-w-[12px] flex flex-col items-center group relative">
                            <div className="w-full flex flex-col-reverse" style={{ height: `${totalH}%`, minHeight: '2px' }}>
                                {sourceKeys.map((s) => {
                                    const cnt = d.sources[s] || 0;
                                    if (!cnt) return null;
                                    const pct = (cnt / d.total) * 100;
                                    return (
                                        <div
                                            key={s}
                                            style={{ height: `${pct}%`, backgroundColor: sourceColor(s) }}
                                            className="w-full first:rounded-t-md transition-all"
                                        />
                                    );
                                })}
                                {d.total === 0 && (
                                    <div className="w-full bg-dark-100 rounded-md h-full"></div>
                                )}
                            </div>
                            <span className={`text-[10px] mt-1 text-dark-500 ${showLabel ? '' : 'invisible'}`}>
                                {dt.toLocaleDateString('fr-CH', { day: '2-digit', month: '2-digit' })}
                            </span>
                            {/* Tooltip on hover */}
                            <div className="hidden group-hover:block absolute bottom-full mb-2 z-10 bg-dark-900 text-white text-xs rounded-lg px-3 py-2 whitespace-nowrap shadow-xl">
                                <div className="font-semibold mb-1">
                                    {dt.toLocaleDateString('fr-CH', { weekday: 'short', day: '2-digit', month: 'short' })}
                                </div>
                                <div className="text-dark-300">{d.total} réservation{d.total > 1 ? 's' : ''}</div>
                                {Object.entries(d.sources).map(([s, c]) => (
                                    <div key={s} className="flex items-center gap-2 mt-1">
                                        <span className="w-2 h-2 rounded-sm" style={{ backgroundColor: sourceColor(s) }}></span>
                                        <span>{sourceLabel(s)}: {c}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

// ============================================================================
// REVENUE BREAKDOWN PAR OUTIL (SMART, TABLET, AGENT, MINI-SITE, IVR)
// ============================================================================

const REVENUE_TOOLS = [
    { source: 'smart', label: 'Smart', icon: 'fa-mobile-screen', color: 'emerald' },
    { source: 'tablet', label: 'Tablet', icon: 'fa-tablet-screen-button', color: 'indigo' },
    { source: 'agent', label: 'Agent', icon: 'fa-headset', color: 'blue' },
    { source: 'minisite', label: 'Mini-site', icon: 'fa-globe', color: 'teal' },
    { source: 'ivr', label: 'IVR', icon: 'fa-phone-volume', color: 'rose' },
    { source: 'gateway', label: 'Gateway (API)', icon: 'fa-code', color: 'slate' }
];

const RevenueByToolBreakdown = ({ bySource }) => {
    const map = {};
    (bySource || []).forEach(row => {
        map[row.source] = row;
    });

    const rows = REVENUE_TOOLS.map(t => {
        const r = map[t.source] || {};
        return {
            ...t,
            total: r.total || 0,
            completed: r.completed || 0,
            cancelled: r.cancelled || 0,
            revenue: parseFloat(r.revenue) || 0
        };
    });

    const totalRevenue = rows.reduce((s, r) => s + r.revenue, 0);
    const maxRevenue = Math.max(1, ...rows.map(r => r.revenue));

    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-5">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Chiffre d'affaires par outil</h3>
                    <p className="text-sm text-dark-500">Détail par canal de réservation</p>
                </div>
                <div className="text-right">
                    <p className="text-xs text-dark-400 uppercase tracking-wider">Total</p>
                    <p className="text-xl font-bold text-dark-900">{fmtMoney(totalRevenue)}</p>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3 mb-5">
                {rows.map(r => {
                    const c = TOOL_COLOR_CLASSES[r.color] || TOOL_COLOR_CLASSES.amber;
                    return (
                        <div key={r.source} className={`rounded-xl border border-dark-100 p-4 ${r.revenue > 0 ? 'bg-white' : 'bg-dark-50'}`}>
                            <div className="flex items-center gap-2 mb-3">
                                <div className={`w-9 h-9 ${c.icon} rounded-lg flex items-center justify-center`}>
                                    <i className={`fas ${r.icon}`}></i>
                                </div>
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold text-dark-900 truncate">{r.label}</p>
                                    <p className="text-[11px] text-dark-500">{r.completed} terminée{r.completed > 1 ? 's' : ''}</p>
                                </div>
                            </div>
                            <p className={`text-xl font-bold ${r.revenue > 0 ? 'text-dark-900' : 'text-dark-400'}`}>
                                {fmtMoney(r.revenue)}
                            </p>
                        </div>
                    );
                })}
            </div>

            <div className="space-y-2">
                {rows.map(r => {
                    const pct = maxRevenue > 0 ? (r.revenue / maxRevenue) * 100 : 0;
                    return (
                        <div key={r.source} className="flex items-center gap-3">
                            <div className="w-20 text-xs font-medium text-dark-600 flex items-center gap-1.5">
                                <i className={`fas ${r.icon} text-[10px]`} style={{ color: sourceColor(r.source) }}></i>
                                {r.label}
                            </div>
                            <div className="flex-1 h-2 bg-dark-100 rounded-full overflow-hidden">
                                <div
                                    className="h-full rounded-full transition-all"
                                    style={{ width: `${pct}%`, backgroundColor: sourceColor(r.source) }}
                                ></div>
                            </div>
                            <div className="w-24 text-right text-xs font-semibold text-dark-700">
                                {fmtMoney(r.revenue)}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

// ============================================================================
// SOURCE BREAKDOWN
// ============================================================================

const SourceBreakdown = ({ bySource, total }) => {
    const sorted = [...(bySource || [])].sort((a, b) => (b.total || 0) - (a.total || 0));
    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <h3 className="text-lg font-bold text-dark-900 mb-4">Répartition par source</h3>
            {sorted.length === 0 ? (
                <p className="text-dark-400 text-sm text-center py-8">Aucune réservation sur la période</p>
            ) : (
                <div className="space-y-3">
                    {sorted.map(row => {
                        const pct = total > 0 ? Math.round((row.total / total) * 100) : 0;
                        return (
                            <div key={row.source}>
                                <div className="flex items-center justify-between mb-1">
                                    <div className="flex items-center gap-2">
                                        <span className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: sourceColor(row.source) }}></span>
                                        <span className="text-sm font-medium text-dark-700">{sourceLabel(row.source)}</span>
                                    </div>
                                    <div className="text-sm text-dark-600">
                                        <span className="font-semibold text-dark-900">{fmtNumber(row.total)}</span>
                                        <span className="text-dark-400 ml-1">({pct}%)</span>
                                    </div>
                                </div>
                                <div className="h-2 bg-dark-100 rounded-full overflow-hidden">
                                    <div
                                        className="h-full rounded-full transition-all"
                                        style={{ width: `${pct}%`, backgroundColor: sourceColor(row.source) }}
                                    ></div>
                                </div>
                                <div className="flex justify-between text-xs text-dark-400 mt-1">
                                    <span>{row.completed || 0} terminée{(row.completed || 0) > 1 ? 's' : ''} · {row.cancelled || 0} annulée{(row.cancelled || 0) > 1 ? 's' : ''}</span>
                                    <span>{fmtMoney(row.revenue)}</span>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// AGENT BREAKDOWN
// ============================================================================

const AgentBreakdown = ({ byAgent, subAccounts }) => {
    const sorted = [...(byAgent || [])].sort((a, b) => (b.total || 0) - (a.total || 0));
    const subByLabel = {};
    (subAccounts || []).forEach(s => {
        if (s.label) subByLabel[s.label.toLowerCase()] = s;
        if (s.username) subByLabel[s.username.toLowerCase()] = s;
    });
    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-4">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Réservations par agent / compte</h3>
                    <p className="text-sm text-dark-500">Basé sur le nom déclaré au moment de la réservation</p>
                </div>
            </div>
            {sorted.length === 0 ? (
                <p className="text-dark-400 text-sm text-center py-8">Aucun agent identifié sur la période</p>
            ) : (
                <div className="space-y-2">
                    {sorted.slice(0, 10).map((row, i) => {
                        const linked = subByLabel[(row.agent_name || '').toLowerCase()];
                        return (
                            <div key={i} className="flex items-center justify-between p-3 bg-dark-50 rounded-xl hover:bg-dark-100 transition">
                                <div className="flex items-center gap-3 min-w-0">
                                    <div className="w-9 h-9 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-sm font-bold flex-shrink-0">
                                        {(row.agent_name || '?').slice(0, 1).toUpperCase()}
                                    </div>
                                    <div className="min-w-0">
                                        <p className="font-semibold text-dark-900 truncate">{row.agent_name || 'Inconnu'}</p>
                                        <p className="text-xs text-dark-500 flex items-center gap-2">
                                            {linked ? (
                                                <>
                                                    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold ${linked.access_type === 'unlimited' ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'}`}>
                                                        {linked.access_type === 'unlimited' ? 'Illimité' : 'Limité'}
                                                    </span>
                                                    @{linked.username}
                                                </>
                                            ) : (
                                                <span className="text-dark-400">Compte non lié</span>
                                            )}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-right flex-shrink-0">
                                    <p className="font-bold text-dark-900">{fmtNumber(row.total)}</p>
                                    <p className="text-xs text-dark-500">{row.completed || 0} terminée{(row.completed || 0) > 1 ? 's' : ''}</p>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// DASHBOARD VIEW
// ============================================================================

const DashboardView = ({ partner, setToast }) => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [days, setDays] = useState(30);

    const load = async (d = days) => {
        setLoading(true);
        try {
            const res = await window.partnerAPI.getDashboard(d);
            if (res.success) {
                setData(res.data);
            } else {
                setToast && setToast({ message: res.error || 'Erreur de chargement', type: 'error' });
            }
        } catch (e) {
            setToast && setToast({ message: 'Erreur de connexion', type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(days); }, [days]);

    if (loading && !data) {
        return (
            <div className="flex items-center justify-center py-20">
                <Spinner size="lg" />
            </div>
        );
    }

    if (!data) return null;

    const { tools = [], stats = {}, totals = {}, period = {}, sub_accounts = [] } = data;
    const dayList = period.day_list || [];
    const enabledToolsCount = tools.filter(t => t.enabled !== false).length;

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between gap-4 flex-wrap">
                <div>
                    <h1 className="text-3xl font-bold text-dark-900">Tableau de bord</h1>
                    <p className="text-dark-500 mt-1">Vue d'ensemble de l'activité de {partner?.name || 'votre établissement'}</p>
                </div>
                <div className="flex items-center gap-2 bg-white rounded-xl p-1 border border-dark-100">
                    {[7, 30, 90].map(d => (
                        <button
                            key={d}
                            onClick={() => setDays(d)}
                            className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${
                                days === d ? 'bg-primary-500 text-white' : 'text-dark-600 hover:bg-dark-100'
                            }`}
                        >
                            {d} jours
                        </button>
                    ))}
                </div>
            </div>

            {/* Stat cards */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <DashStatCard icon="fa-list-check" label="Réservations" value={fmtNumber(totals.total)} sublabel={`Sur ${days} jours`} color="primary" />
                <DashStatCard icon="fa-circle-check" label="Terminées" value={fmtNumber(totals.completed)} color="emerald" />
                <DashStatCard icon="fa-circle-xmark" label="Annulées" value={fmtNumber(totals.cancelled)} color="rose" />
            </div>

            {/* Chiffre d'affaires par outil */}
            <RevenueByToolBreakdown bySource={stats.by_source || []} />

            {/* Chart + repartition */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="lg:col-span-2">
                    <DailyChart dayList={dayList} perDay={stats.per_day || []} sources={stats.by_source || []} />
                </div>
                <div>
                    <SourceBreakdown bySource={stats.by_source || []} total={totals.total || 0} />
                </div>
            </div>

            {/* Agent breakdown */}
            <AgentBreakdown byAgent={stats.by_agent || []} subAccounts={sub_accounts} />

            {/* Tools */}
            <div>
                <div className="flex items-center justify-between mb-4">
                    <div>
                        <h2 className="text-2xl font-bold text-dark-900">Outils Partenaire</h2>
                        <p className="text-dark-500 text-sm mt-1">{enabledToolsCount} outil{enabledToolsCount > 1 ? 's' : ''} disponible{enabledToolsCount > 1 ? 's' : ''}</p>
                    </div>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    {tools.map(t => <ToolCard key={t.id} tool={t} />)}
                </div>
            </div>
        </div>
    );
};
