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 ContactRow = {
    id: number;
    full_name: string;
    job_title: string | null;
    email: string | null;
    phone: string | null;
    mobile: string | null;
    is_primary: boolean;
    last_contacted_at: string | null;
    activities_count: number;
    company: {
        id: number;
        name: string;
        city: string | null;
        status: string;
    };
};

type Props = PageProps<{
    contacts: Paginated<ContactRow>;
    filters: { search: string };
    stats: {
        total: number;
        primary: number;
        recentlyContacted: number;
        companies: number;
    };
}>;

export default function ContactsIndex({ contacts, filters, stats }: Props) {
    const [search, setSearch] = useState(filters.search);
    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        router.get(route('contacts.index'), { search }, { preserveState: true });
    };

    return (
        <AuthenticatedLayout
            header={
                <PageHeader
                    title="Contacts"
                    subtitle="Interlocuteurs et suivi de la relation commerciale"
                    actionHref={route('companies.index')}
                    actionLabel="Voir les entreprises"
                />
            }
        >
            <Head title="Contacts 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 sm:grid-cols-2 xl:grid-cols-4">
                    <Kpi label="Contacts enregistrés" value={stats.total} tone="blue" />
                    <Kpi label="Contacts principaux" value={stats.primary} tone="green" />
                    <Kpi label="Contactés récemment" value={stats.recentlyContacted} tone="amber" />
                    <Kpi label="Entreprises couvertes" value={stats.companies} tone="purple" />
                </section>

                <section className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                    <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-100 px-5 py-4">
                        <div>
                            <h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">
                                Annuaire des contacts
                            </h2>
                            <p className="mt-1 text-xs text-slate-500">
                                {contacts.total} contacts associés à vos comptes CRM
                            </p>
                        </div>
                        <form onSubmit={submit} className="flex gap-2">
                            <input
                                value={search}
                                onChange={(event) => setSearch(event.target.value)}
                                placeholder="Nom, email, entreprise..."
                                className="w-64 rounded-lg border-slate-200 text-sm focus:border-blue-500 focus:ring-blue-500"
                            />
                            <button className="rounded-lg bg-[#12529c] px-4 py-2 text-sm font-semibold text-white">
                                Rechercher
                            </button>
                        </form>
                    </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">Contact</th>
                                    <th className="px-5 py-3 text-left">Entreprise</th>
                                    <th className="px-5 py-3 text-left">Coordonnées</th>
                                    <th className="px-5 py-3 text-left">Dernier contact</th>
                                    <th className="px-5 py-3 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {contacts.data.length === 0 && (
                                    <tr>
                                        <td colSpan={5} className="px-5 py-12 text-center text-slate-500">
                                            Aucun contact ne correspond à votre recherche.
                                        </td>
                                    </tr>
                                )}
                                {contacts.data.map((contact) => (
                                    <tr key={contact.id} className="hover:bg-slate-50/70">
                                        <td className="px-5 py-4">
                                            <div className="flex items-center gap-3">
                                                <span className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-50 font-bold text-blue-700">
                                                    {initials(contact.full_name)}
                                                </span>
                                                <div>
                                                    <p className="font-semibold text-slate-900">{contact.full_name}</p>
                                                    <p className="text-xs text-slate-500">
                                                        {contact.job_title ?? 'Fonction non renseignée'}
                                                        {contact.is_primary && ' - Principal'}
                                                    </p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-5 py-4">
                                            <p className="font-medium text-slate-800">{contact.company.name}</p>
                                            <p className="text-xs text-slate-500">{contact.company.city ?? 'Ville inconnue'}</p>
                                        </td>
                                        <td className="px-5 py-4 text-slate-600">
                                            <p>{contact.email ?? '-'}</p>
                                            <p className="text-xs">{contact.phone ?? contact.mobile ?? '-'}</p>
                                        </td>
                                        <td className="px-5 py-4 text-slate-600">
                                            <p>{formatDate(contact.last_contacted_at)}</p>
                                            <p className="text-xs text-blue-700">
                                                {contact.activities_count} activité(s)
                                            </p>
                                        </td>
                                        <td className="px-5 py-4 text-center">
                                            <Link
                                                href={route('companies.show', contact.company.id)}
                                                className="rounded-lg border border-blue-200 px-3 py-2 text-xs font-semibold text-blue-700 hover:bg-blue-50"
                                            >
                                                Ouvrir la fiche
                                            </Link>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>
            </div>
        </AuthenticatedLayout>
    );
}

function PageHeader({
    title,
    subtitle,
    actionHref,
    actionLabel,
}: {
    title: string;
    subtitle: string;
    actionHref: string;
    actionLabel: string;
}) {
    return (
        <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">{subtitle}</p>
            </div>
            <Link href={actionHref} className="rounded-lg bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white">
                {actionLabel}
            </Link>
        </div>
    );
}

function Kpi({ label, value, tone }: { label: string; value: number; tone: string }) {
    const styles: Record<string, string> = {
        blue: 'bg-blue-100 text-blue-700',
        green: 'bg-emerald-100 text-emerald-700',
        amber: 'bg-amber-100 text-amber-700',
        purple: 'bg-violet-100 text-violet-700',
    };

    return (
        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <span className={`inline-flex rounded-full px-3 py-1 text-xs font-bold uppercase ${styles[tone]}`}>
                {label}
            </span>
            <p className="mt-3 text-3xl font-bold text-[#062853]">{value}</p>
        </div>
    );
}

function initials(name: string) {
    return name
        .split(' ')
        .slice(0, 2)
        .map((value) => value.slice(0, 1))
        .join('')
        .toUpperCase();
}

function formatDate(date: string | null) {
    return date ? new Date(date).toLocaleDateString('fr-FR') : 'Jamais contacté';
}
