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

type Props = PageProps<{
    stats: {
        companies: number;
        contacts: number;
        activities: number;
        completedActivities: number;
        customers: number;
        estimatedPotential: number;
    };
    activityByType: Array<{ type: string; label: string; total: number }>;
    topCities: Array<{ city: string; total: number }>;
}>;

export default function Statistics({ stats, activityByType, topCities }: Props) {
    const maxActivity = Math.max(...activityByType.map((item) => item.total), 1);
    const maxCity = Math.max(...topCities.map((item) => item.total), 1);
    const completionRate = stats.activities > 0
        ? Math.round((stats.completedActivities / stats.activities) * 100)
        : 0;

    return (
        <AuthenticatedLayout
            header={
                <div>
                    <h1 className="text-2xl font-bold text-[#062853]">Statistiques</h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Performance commerciale issue des données CRM enregistrées
                    </p>
                </div>
            }
        >
            <Head title="Statistiques CRM" />
            <div className="mx-auto max-w-[1500px] space-y-5 px-4 py-5 sm:px-6 lg:px-7">
                <section className="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
                    <Summary label="Entreprises" value={formatNumber(stats.companies)} />
                    <Summary label="Contacts" value={formatNumber(stats.contacts)} />
                    <Summary label="Activités" value={formatNumber(stats.activities)} />
                    <Summary label="Terminées" value={formatNumber(stats.completedActivities)} />
                    <Summary label="Clients" value={formatNumber(stats.customers)} />
                    <Summary label="Potentiel" value={formatCurrency(stats.estimatedPotential)} />
                </section>
                <div className="grid gap-5 xl:grid-cols-3">
                    <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm xl:col-span-2">
                        <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">
                            Activité par canal
                        </h2>
                        <p className="mt-1 text-xs text-slate-500">Types d’interaction enregistrés</p>
                        <div className="mt-7 space-y-5">
                            {activityByType.map((item, index) => (
                                <Bar
                                    key={item.type}
                                    label={item.label}
                                    value={item.total}
                                    width={(item.total / maxActivity) * 100}
                                    color={['bg-blue-600', 'bg-emerald-500', 'bg-violet-500', 'bg-amber-500', 'bg-teal-500'][index]}
                                />
                            ))}
                        </div>
                    </section>
                    <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">
                            Indicateurs clés
                        </h2>
                        <div className="mt-6 space-y-5">
                            <Indicator label="Taux de réalisation" value={`${completionRate}%`} />
                            <Indicator
                                label="Conversion entreprise → client"
                                value={`${stats.companies > 0 ? Math.round((stats.customers / stats.companies) * 100) : 0}%`}
                            />
                            <Indicator
                                label="Activités par contact"
                                value={stats.contacts > 0 ? (stats.activities / stats.contacts).toFixed(1) : '0'}
                            />
                        </div>
                    </section>
                </div>
                <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">
                        Répartition par zone
                    </h2>
                    <div className="mt-6 grid gap-5 md:grid-cols-2 xl:grid-cols-5">
                        {topCities.length === 0 && (
                            <p className="text-sm text-slate-500">Aucune ville renseignée.</p>
                        )}
                        {topCities.map((city) => (
                            <div key={city.city}>
                                <div className="mb-2 flex justify-between text-sm">
                                    <span className="font-semibold text-slate-700">{city.city}</span>
                                    <span>{city.total}</span>
                                </div>
                                <div className="h-2 rounded-full bg-slate-100">
                                    <div className="h-2 rounded-full bg-emerald-500" style={{ width: `${(city.total / maxCity) * 100}%` }} />
                                </div>
                            </div>
                        ))}
                    </div>
                </section>
            </div>
        </AuthenticatedLayout>
    );
}

function Summary({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <p className="text-xs font-bold uppercase text-slate-500">{label}</p>
            <p className="mt-3 text-2xl font-bold text-[#062853]">{value}</p>
        </div>
    );
}

function Bar({ label, value, width, color }: { label: string; value: number; width: number; color: string }) {
    return (
        <div>
            <div className="mb-2 flex justify-between text-sm">
                <span className="font-semibold text-slate-700">{label}</span>
                <span className="text-slate-500">{value}</span>
            </div>
            <div className="h-3 rounded-full bg-slate-100">
                <div className={`h-3 rounded-full ${color}`} style={{ width: `${Math.max(width, value > 0 ? 4 : 0)}%` }} />
            </div>
        </div>
    );
}

function Indicator({ label, value }: { label: string; value: string }) {
    return (
        <div className="flex items-center justify-between border-b border-slate-100 pb-4 text-sm last:border-none">
            <span className="text-slate-600">{label}</span>
            <span className="font-bold text-emerald-700">{value}</span>
        </div>
    );
}

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',
        maximumFractionDigits: 0,
    }).format(value);
}
