import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types';
import { Paginated } from '@/types/crm';
import { Head, Link, router } from '@inertiajs/react';
import { FormEventHandler, useState } from 'react';

type ActivityRow = {
    id: number;
    subject: string;
    details: string | null;
    type: string;
    status: string;
    due_at: string | null;
    created_at: string;
    company: { id: number; name: string; city: string | null };
    contact?: { full_name?: string; first_name: string | null; last_name: string | null };
    user?: { id: number; name: string };
};

type Props = PageProps<{
    mode: 'relances' | 'appels' | 'taches';
    title: string;
    activities: Paginated<ActivityRow>;
    filters: { search: string; status: string };
    typeLabels: Record<string, string>;
    statusLabels: Record<string, string>;
    stats: {
        total: number;
        open: number;
        overdue: number;
        plannedThisWeek: number;
        done: number;
    };
}>;

export default function ActivitiesIndex({
    mode,
    title,
    activities,
    filters,
    typeLabels,
    statusLabels,
    stats,
}: Props) {
    const [localFilters, setLocalFilters] = useState(filters);
    const routeName = {
        relances: 'activities.follow-ups',
        appels: 'activities.calls',
        taches: 'activities.tasks',
    }[mode];
    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        router.get(route(routeName), localFilters, { preserveState: true });
    };

    return (
        <AuthenticatedLayout
            header={
                <div className="flex flex-wrap items-center justify-between gap-4">
                    <div>
                        <h1 className="text-2xl font-bold text-[#062853]">{title}</h1>
                        <p className="mt-1 text-sm text-slate-500">
                            Suivi opérationnel des {title.toLowerCase()} enregistrés
                        </p>
                    </div>
                    <Link
                        href={route('companies.index')}
                        className="rounded-lg bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white"
                    >
                        + Choisir une entreprise
                    </Link>
                </div>
            }
        >
            <Head title={`${title} CRM`} />
            <div className="mx-auto max-w-[1500px] space-y-5 px-4 py-5 sm:px-6 lg:px-7">
                <nav className="flex gap-6 border-b border-slate-200 text-sm font-semibold text-slate-500">
                    {[
                        ['activities.follow-ups', 'Relances'],
                        ['activities.calls', 'Appels'],
                        ['activities.tasks', 'Tâches'],
                    ].map(([href, label]) => (
                        <Link
                            key={href}
                            href={route(href)}
                            className={`border-b-2 pb-3 ${label === title ? 'border-blue-600 text-blue-700' : 'border-transparent'}`}
                        >
                            {label}
                        </Link>
                    ))}
                </nav>
                <section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
                    <Metric label="Total" value={stats.total} tone="blue" />
                    <Metric label="À faire" value={stats.open} tone="amber" />
                    <Metric label="En retard" value={stats.overdue} tone="rose" />
                    <Metric label="Cette semaine" value={stats.plannedThisWeek} tone="green" />
                    <Metric label="Terminées" value={stats.done} tone="purple" />
                </section>
                <div className="grid gap-5 lg:grid-cols-[245px_1fr]">
                    <form
                        onSubmit={submit}
                        className="h-fit space-y-5 rounded-xl border border-slate-200 bg-white p-5 shadow-sm"
                    >
                        <h2 className="text-xs font-bold uppercase tracking-widest text-[#062853]">Filtres</h2>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Recherche</label>
                            <input
                                value={localFilters.search}
                                onChange={(event) =>
                                    setLocalFilters((current) => ({ ...current, search: event.target.value }))
                                }
                                placeholder="Sujet ou entreprise"
                                className="mt-2 w-full rounded-lg border-slate-200 text-sm"
                            />
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Statut</label>
                            <select
                                value={localFilters.status}
                                onChange={(event) =>
                                    setLocalFilters((current) => ({ ...current, status: event.target.value }))
                                }
                                className="mt-2 w-full rounded-lg border-slate-200 text-sm"
                            >
                                <option value="">Tous les statuts</option>
                                {Object.entries(statusLabels).map(([value, label]) => (
                                    <option key={value} value={value}>{label}</option>
                                ))}
                            </select>
                        </div>
                        <button className="w-full rounded-lg bg-[#12529c] py-2.5 text-sm font-semibold text-white">
                            Appliquer les filtres
                        </button>
                    </form>
                    <section className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                        <div className="border-b border-slate-100 px-5 py-4">
                            <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">
                                Liste des {title.toLowerCase()}
                            </h2>
                            <p className="mt-1 text-xs text-slate-500">{activities.total} éléments suivis</p>
                        </div>
                        <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">Action</th>
                                        <th className="px-5 py-3 text-left">Entreprise</th>
                                        <th className="px-5 py-3 text-left">Type</th>
                                        <th className="px-5 py-3 text-left">Échéance</th>
                                        <th className="px-5 py-3 text-left">Statut</th>
                                        <th className="px-5 py-3 text-left">Responsable</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100">
                                    {activities.data.length === 0 && (
                                        <tr>
                                            <td colSpan={6} className="px-5 py-12 text-center text-slate-500">
                                                Aucune activité enregistrée pour cette vue.
                                            </td>
                                        </tr>
                                    )}
                                    {activities.data.map((activity) => (
                                        <tr key={activity.id} className="hover:bg-slate-50/70">
                                            <td className="px-5 py-4">
                                                <p className="font-semibold text-slate-900">{activity.subject}</p>
                                                <p className="max-w-xs truncate text-xs text-slate-500">
                                                    {activity.details ?? 'Aucun détail'}
                                                </p>
                                            </td>
                                            <td className="px-5 py-4">
                                                <Link
                                                    href={route('companies.show', activity.company.id)}
                                                    className="font-medium text-blue-700"
                                                >
                                                    {activity.company.name}
                                                </Link>
                                                <p className="text-xs text-slate-500">{activity.company.city ?? '-'}</p>
                                            </td>
                                            <td className="px-5 py-4 text-slate-600">
                                                {typeLabels[activity.type] ?? activity.type}
                                            </td>
                                            <td className="px-5 py-4 text-slate-600">
                                                {formatDate(activity.due_at)}
                                            </td>
                                            <td className="px-5 py-4">
                                                <Status status={activity.status} label={statusLabels[activity.status] ?? activity.status} />
                                            </td>
                                            <td className="px-5 py-4 text-slate-600">
                                                {activity.user?.name ?? 'Non assigné'}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </section>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

function Metric({ label, value, tone }: { label: string; value: number; tone: string }) {
    const colors: Record<string, string> = {
        blue: 'text-blue-700 bg-blue-50',
        amber: 'text-amber-700 bg-amber-50',
        rose: 'text-rose-700 bg-rose-50',
        green: 'text-emerald-700 bg-emerald-50',
        purple: 'text-violet-700 bg-violet-50',
    };
    return (
        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <span className={`rounded-full px-3 py-1 text-xs font-bold uppercase ${colors[tone]}`}>{label}</span>
            <p className="mt-3 text-3xl font-bold text-[#062853]">{value}</p>
        </div>
    );
}

function Status({ status, label }: { status: string; label: string }) {
    const style = status === 'done'
        ? 'bg-emerald-50 text-emerald-700'
        : status === 'cancelled'
          ? 'bg-slate-100 text-slate-600'
          : 'bg-amber-50 text-amber-700';
    return <span className={`rounded-full px-3 py-1 text-xs font-semibold ${style}`}>{label}</span>;
}

function formatDate(date: string | null) {
    return date
        ? new Date(date).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' })
        : 'Non planifiée';
}
