import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types';
import { Head, Link, usePage } from '@inertiajs/react';

type DashboardProps = PageProps<{
    stats: {
        totalCompanies: number;
        totalProspects: number;
        totalLeads: number;
        totalCustomers: number;
        totalInactive: number;
        upcomingActivities: number;
        overdueActivities: number;
        estimatedPotential: number;
    };
    activityStats: {
        open: number;
        done: number;
        cancelled: number;
    };
    statusLabels: Record<string, string>;
    topZones: Array<{
        city: string;
        total: number;
        prospects: number;
        leads: number;
        customers: number;
    }>;
    recentCompanies: Array<{
        id: number;
        name: string;
        city: string | null;
        status: string;
        created_at: string;
    }>;
    recentActivities: Array<{
        id: number;
        subject: string;
        status: string;
        type: string;
        due_at: string | null;
        created_at: string;
        company?: {
            id: number;
            name: string;
        };
    }>;
}>;

type Tone = 'blue' | 'green' | 'amber' | 'purple' | 'slate' | 'rose';

const toneClasses: Record<Tone, { icon: string; text: string; bar: string }> = {
    blue: {
        icon: 'bg-blue-100 text-blue-700',
        text: 'text-blue-700',
        bar: 'bg-blue-600',
    },
    green: {
        icon: 'bg-emerald-100 text-emerald-700',
        text: 'text-emerald-700',
        bar: 'bg-emerald-500',
    },
    amber: {
        icon: 'bg-amber-100 text-amber-700',
        text: 'text-amber-700',
        bar: 'bg-amber-500',
    },
    purple: {
        icon: 'bg-violet-100 text-violet-700',
        text: 'text-violet-700',
        bar: 'bg-violet-500',
    },
    slate: {
        icon: 'bg-slate-100 text-slate-600',
        text: 'text-slate-600',
        bar: 'bg-slate-400',
    },
    rose: {
        icon: 'bg-rose-100 text-rose-700',
        text: 'text-rose-700',
        bar: 'bg-rose-500',
    },
};

export default function Dashboard({
    stats,
    activityStats,
    statusLabels,
    topZones,
    recentCompanies,
    recentActivities,
}: DashboardProps) {
    const page = usePage<PageProps>();
    const activityTotal =
        activityStats.open + activityStats.done + activityStats.cancelled;
    const largestZone = Math.max(...topZones.map((zone) => zone.total), 1);
    const contactRate = percentage(stats.totalCustomers + stats.totalLeads, stats.totalCompanies);

    return (
        <AuthenticatedLayout
            header={
                <div className="flex flex-wrap items-center justify-between gap-4">
                    <div>
                        <p className="text-xs font-bold uppercase tracking-[0.16em] text-blue-700">
                            Pilotage commercial
                        </p>
                        <h1 className="mt-1 text-xl font-bold text-[#062853]">
                            Tableau de bord - Vue nationale
                        </h1>
                    </div>
                    <div className="flex flex-wrap items-center gap-3">
                        <Link
                            href={route('companies.import.create')}
                            className="rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-blue-300"
                        >
                            Importer
                        </Link>
                        <Link
                            href={route('companies.create')}
                            className="rounded-lg bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-emerald-700"
                        >
                            + Nouveau prospect
                        </Link>
                    </div>
                </div>
            }
        >
            <Head title="Tableau de bord CRM" />

            <div className="mx-auto max-w-[1500px] space-y-5 px-4 py-5 sm:px-6 lg:px-7">
                {page.props.flash?.success && (
                    <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
                        {page.props.flash.success}
                    </div>
                )}

                <section
                    aria-label="Indicateurs CRM"
                    className="grid gap-3 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-7"
                >
                    <StatCard
                        label="Total entreprises"
                        value={formatNumber(stats.totalCompanies)}
                        icon="E"
                        tone="blue"
                        subline="Base CRM"
                    />
                    <StatCard
                        label="Prospects"
                        value={formatNumber(stats.totalProspects)}
                        icon="P"
                        tone="amber"
                        subline={percentage(stats.totalProspects, stats.totalCompanies)}
                    />
                    <StatCard
                        label="Leads qualifiés"
                        value={formatNumber(stats.totalLeads)}
                        icon="L"
                        tone="purple"
                        subline={percentage(stats.totalLeads, stats.totalCompanies)}
                    />
                    <StatCard
                        label="Clients"
                        value={formatNumber(stats.totalCustomers)}
                        icon="C"
                        tone="green"
                        subline={percentage(stats.totalCustomers, stats.totalCompanies)}
                    />
                    <StatCard
                        label="À relancer"
                        value={formatNumber(stats.upcomingActivities)}
                        icon="R"
                        tone="amber"
                        subline="7 prochains jours"
                    />
                    <StatCard
                        label="En retard"
                        value={formatNumber(stats.overdueActivities)}
                        icon="!"
                        tone={stats.overdueActivities > 0 ? 'rose' : 'slate'}
                        subline="Action requise"
                    />
                    <StatCard
                        label="Potentiel"
                        value={formatCurrency(stats.estimatedPotential)}
                        icon="EUR"
                        tone="green"
                        subline="Pipeline estimé"
                    />
                </section>

                <div className="grid gap-5 xl:grid-cols-12">
                    <section className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm xl:col-span-8">
                        <PanelHeader
                            title="Couverture commerciale"
                            description="Répartition de la prospection par zone active"
                        />
                        <div className="grid gap-5 p-5 lg:grid-cols-[1fr_310px]">
                            <div className="rounded-xl border border-slate-100 bg-[#f7fafc] p-5">
                                <div className="mb-5 flex items-center justify-between gap-3">
                                    <span className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-[#062853]">
                                        France entière
                                    </span>
                                    <span className="text-xs font-medium text-slate-500">
                                        {topZones.length} zones principales
                                    </span>
                                </div>
                                {topZones.length === 0 ? (
                                    <EmptyState text="Ajoutez des entreprises pour visualiser la couverture." />
                                ) : (
                                    <div className="space-y-4">
                                        {topZones.map((zone, index) => (
                                            <div key={zone.city}>
                                                <div className="mb-1.5 flex justify-between text-sm">
                                                    <span className="font-semibold text-slate-700">
                                                        {index + 1}. {zone.city}
                                                    </span>
                                                    <span className="text-slate-500">
                                                        {formatNumber(zone.total)} entreprises
                                                    </span>
                                                </div>
                                                <div className="h-3 overflow-hidden rounded-full bg-slate-200">
                                                    <div
                                                        className="h-full rounded-full bg-gradient-to-r from-emerald-500 via-lime-400 to-amber-400"
                                                        style={{
                                                            width: `${Math.max((zone.total / largestZone) * 100, 10)}%`,
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                                <p className="mt-5 text-xs text-slate-500">
                                    Intensité calculée à partir des entreprises enregistrées.
                                </p>
                            </div>

                            <div className="overflow-hidden rounded-xl border border-slate-200">
                                <div className="bg-[#062853] px-5 py-4 text-white">
                                    <p className="text-xs font-semibold uppercase tracking-widest text-blue-200">
                                        Pipeline national
                                    </p>
                                    <p className="mt-1 text-xl font-bold">
                                        {formatNumber(stats.totalCompanies)} comptes
                                    </p>
                                    <span className="mt-3 inline-flex rounded-full bg-emerald-500/20 px-3 py-1 text-xs font-semibold text-emerald-200">
                                        {contactRate} engagés
                                    </span>
                                </div>
                                <div className="space-y-4 p-5">
                                    <PipelineRow
                                        label="Prospects"
                                        value={stats.totalProspects}
                                        total={stats.totalCompanies}
                                        tone="amber"
                                    />
                                    <PipelineRow
                                        label="Leads qualifiés"
                                        value={stats.totalLeads}
                                        total={stats.totalCompanies}
                                        tone="purple"
                                    />
                                    <PipelineRow
                                        label="Clients"
                                        value={stats.totalCustomers}
                                        total={stats.totalCompanies}
                                        tone="green"
                                    />
                                    <PipelineRow
                                        label="Inactifs"
                                        value={stats.totalInactive}
                                        total={stats.totalCompanies}
                                        tone="slate"
                                    />
                                    <Link
                                        href={route('companies.index')}
                                        className="block rounded-lg bg-[#12529c] px-4 py-2.5 text-center text-sm font-semibold text-white transition hover:bg-[#0c417e]"
                                    >
                                        Voir la liste des entreprises
                                    </Link>
                                </div>
                            </div>
                        </div>
                    </section>

                    <div className="space-y-5 xl:col-span-4">
                        <section className="rounded-xl border border-slate-200 bg-white shadow-sm">
                            <PanelHeader
                                title="Relances et activités"
                                description="Suivi des actions enregistrées"
                            />
                            <div className="flex flex-col items-center gap-6 p-5 sm:flex-row xl:flex-col 2xl:flex-row">
                                <Donut
                                    total={activityTotal}
                                    open={activityStats.open}
                                    done={activityStats.done}
                                    cancelled={activityStats.cancelled}
                                />
                                <div className="w-full space-y-3 text-sm">
                                    <LegendRow
                                        label="Ouvertes"
                                        value={activityStats.open}
                                        color="bg-amber-500"
                                    />
                                    <LegendRow
                                        label="Terminées"
                                        value={activityStats.done}
                                        color="bg-emerald-500"
                                    />
                                    <LegendRow
                                        label="Annulées"
                                        value={activityStats.cancelled}
                                        color="bg-slate-400"
                                    />
                                </div>
                            </div>
                        </section>

                        <section className="rounded-xl border border-slate-200 bg-white shadow-sm">
                            <PanelHeader
                                title="Actions prioritaires"
                                description="Échéances de la semaine"
                            />
                            <div className="grid grid-cols-2 gap-3 p-5">
                                <PriorityCard
                                    label="À planifier"
                                    value={stats.upcomingActivities}
                                    tone="amber"
                                />
                                <PriorityCard
                                    label="En retard"
                                    value={stats.overdueActivities}
                                    tone={stats.overdueActivities > 0 ? 'rose' : 'green'}
                                />
                            </div>
                        </section>
                    </div>
                </div>

                <div className="grid gap-5 xl:grid-cols-12">
                    <section className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm xl:col-span-5">
                        <PanelHeader
                            title="Top 5 zones"
                            description="Performance du pipeline par ville"
                        />
                        <div className="overflow-x-auto">
                            <table className="min-w-full text-sm">
                                <thead className="bg-slate-50 text-xs uppercase tracking-wider text-slate-500">
                                    <tr>
                                        <th className="px-5 py-3 text-left font-semibold">Zone</th>
                                        <th className="px-3 py-3 text-right font-semibold">Total</th>
                                        <th className="px-3 py-3 text-right font-semibold">Leads</th>
                                        <th className="px-5 py-3 text-right font-semibold">Clients</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100">
                                    {topZones.length === 0 && (
                                        <tr>
                                            <td colSpan={4} className="px-5 py-8 text-center text-slate-500">
                                                Aucune zone renseignée.
                                            </td>
                                        </tr>
                                    )}
                                    {topZones.map((zone) => (
                                        <tr key={zone.city}>
                                            <td className="px-5 py-3 font-semibold text-slate-700">
                                                {zone.city}
                                            </td>
                                            <td className="px-3 py-3 text-right">{zone.total}</td>
                                            <td className="px-3 py-3 text-right text-violet-700">
                                                {zone.leads}
                                            </td>
                                            <td className="px-5 py-3 text-right font-semibold text-emerald-700">
                                                {zone.customers}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </section>

                    <section className="rounded-xl border border-slate-200 bg-white shadow-sm xl:col-span-3">
                        <PanelHeader
                            title="Dernières entreprises"
                            description="Nouveaux comptes CRM"
                        />
                        <div className="space-y-2 p-4">
                            {recentCompanies.length === 0 && (
                                <EmptyState text="Aucune entreprise pour le moment." />
                            )}
                            {recentCompanies.slice(0, 5).map((company) => (
                                <Link
                                    key={company.id}
                                    href={route('companies.show', company.id)}
                                    className="flex items-center justify-between gap-2 rounded-lg border border-slate-100 px-3 py-2.5 transition hover:border-blue-200 hover:bg-blue-50"
                                >
                                    <span className="min-w-0">
                                        <span className="block truncate text-sm font-semibold text-slate-800">
                                            {company.name}
                                        </span>
                                        <span className="block truncate text-xs text-slate-500">
                                            {company.city ?? 'Zone inconnue'}
                                        </span>
                                    </span>
                                    <StatusBadge label={statusLabels[company.status] ?? company.status} />
                                </Link>
                            ))}
                        </div>
                    </section>

                    <section className="rounded-xl border border-slate-200 bg-white shadow-sm xl:col-span-4">
                        <PanelHeader
                            title="Dernières actions"
                            description="Journal de suivi commercial"
                        />
                        <div className="divide-y divide-slate-100 px-5">
                            {recentActivities.length === 0 && (
                                <div className="py-7">
                                    <EmptyState text="Aucune activité enregistrée." />
                                </div>
                            )}
                            {recentActivities.slice(0, 5).map((activity) => (
                                <div key={activity.id} className="flex items-start gap-3 py-3">
                                    <span className="mt-1 h-2.5 w-2.5 shrink-0 rounded-full bg-blue-600" />
                                    <div className="min-w-0 flex-1">
                                        <p className="truncate text-sm font-semibold text-slate-800">
                                            {activity.subject}
                                        </p>
                                        <p className="truncate text-xs text-slate-500">
                                            {activity.company?.name ?? 'Entreprise supprimée'}
                                            {activity.due_at
                                                ? ` - ${new Date(activity.due_at).toLocaleDateString('fr-FR')}`
                                                : ''}
                                        </p>
                                    </div>
                                    <StatusBadge label={activity.type} />
                                </div>
                            ))}
                        </div>
                    </section>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

function StatCard({
    label,
    value,
    icon,
    tone,
    subline,
}: {
    label: string;
    value: string;
    icon: string;
    tone: Tone;
    subline: string;
}) {
    return (
        <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div className="flex items-start gap-3">
                <span
                    className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-sm font-bold ${toneClasses[tone].icon}`}
                >
                    {icon}
                </span>
                <div className="min-w-0">
                    <p className="text-[11px] font-semibold uppercase tracking-wide text-slate-500">
                        {label}
                    </p>
                    <p className="mt-1 truncate text-2xl font-bold text-[#0c2446]">{value}</p>
                    <p className={`mt-1 text-xs font-semibold ${toneClasses[tone].text}`}>
                        {subline}
                    </p>
                </div>
            </div>
        </div>
    );
}

function PanelHeader({ title, description }: { title: string; description: string }) {
    return (
        <div className="border-b border-slate-100 px-5 py-4">
            <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">{title}</h2>
            <p className="mt-1 text-xs text-slate-500">{description}</p>
        </div>
    );
}

function PipelineRow({
    label,
    value,
    total,
    tone,
}: {
    label: string;
    value: number;
    total: number;
    tone: Tone;
}) {
    const ratio = numericPercentage(value, total);

    return (
        <div>
            <div className="mb-2 flex justify-between text-sm">
                <span className="font-medium text-slate-600">{label}</span>
                <span className="font-bold text-slate-800">
                    {formatNumber(value)} <span className="text-xs text-slate-400">{ratio}%</span>
                </span>
            </div>
            <div className="h-2 rounded-full bg-slate-100">
                <div
                    className={`h-2 rounded-full ${toneClasses[tone].bar}`}
                    style={{ width: `${ratio}%` }}
                />
            </div>
        </div>
    );
}

function Donut({
    total,
    open,
    done,
    cancelled,
}: {
    total: number;
    open: number;
    done: number;
    cancelled: number;
}) {
    const openPoint = numericPercentage(open, total);
    const donePoint = openPoint + numericPercentage(done, total);
    const background =
        total === 0
            ? '#e2e8f0'
            : `conic-gradient(#f59e0b 0% ${openPoint}%, #10b981 ${openPoint}% ${donePoint}%, #94a3b8 ${donePoint}% 100%)`;

    return (
        <div
            className="relative flex h-36 w-36 shrink-0 items-center justify-center rounded-full"
            style={{ background }}
        >
            <div className="flex h-24 w-24 flex-col items-center justify-center rounded-full bg-white">
                <span className="text-2xl font-bold text-[#062853]">{formatNumber(total)}</span>
                <span className="text-xs text-slate-500">actions</span>
            </div>
        </div>
    );
}

function LegendRow({
    label,
    value,
    color,
}: {
    label: string;
    value: number;
    color: string;
}) {
    return (
        <div className="flex items-center justify-between gap-5">
            <span className="flex items-center gap-2 text-slate-600">
                <span className={`h-2.5 w-2.5 rounded-full ${color}`} />
                {label}
            </span>
            <span className="font-bold text-slate-800">{formatNumber(value)}</span>
        </div>
    );
}

function PriorityCard({
    label,
    value,
    tone,
}: {
    label: string;
    value: number;
    tone: Tone;
}) {
    return (
        <div className="rounded-lg border border-slate-100 bg-slate-50 p-4">
            <p className="text-xs font-semibold uppercase text-slate-500">{label}</p>
            <p className={`mt-2 text-3xl font-bold ${toneClasses[tone].text}`}>
                {formatNumber(value)}
            </p>
        </div>
    );
}

function StatusBadge({ label }: { label: string }) {
    return (
        <span className="shrink-0 rounded-full bg-blue-50 px-2 py-1 text-[10px] font-bold uppercase text-blue-700">
            {label}
        </span>
    );
}

function EmptyState({ text }: { text: string }) {
    return <p className="rounded-lg bg-slate-50 px-4 py-5 text-center text-sm text-slate-500">{text}</p>;
}

function numericPercentage(value: number, total: number) {
    return total > 0 ? Math.round((value / total) * 100) : 0;
}

function percentage(value: number, total: number) {
    return `${numericPercentage(value, total)}%`;
}

function formatNumber(value: number) {
    return new Intl.NumberFormat('fr-FR').format(value);
}

function formatCurrency(value: number) {
    return new Intl.NumberFormat('fr-FR', {
        style: 'currency',
        currency: 'EUR',
        notation: value >= 1000000 ? 'compact' : 'standard',
        maximumFractionDigits: 1,
    }).format(value);
}
