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

type Props = PageProps<{
    opportunities: Paginated<CompanyProposal>;
    filters: { search: string };
    statusLabels: Record<string, string>;
    stats: {
        open: number;
        draft: number;
        sent: number;
        potentialAmount: number;
        weightedAmount: number;
    };
}>;

export default function OpportunitiesIndex({ opportunities, filters, statusLabels, stats }: Props) {
    const [search, setSearch] = useState(filters.search);
    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        router.get(route('opportunities.index'), { search }, { 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]">Opportunités</h1>
                        <p className="mt-1 text-sm text-slate-500">Pipeline des propositions en cours de qualification</p>
                    </div>
                    <Link href={route('proposals.index')} className="rounded-lg bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white">
                        + Créer un devis
                    </Link>
                </div>
            }
        >
            <Head title="Opportunités 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-5">
                    <Metric label="Ouvertes" value={number(stats.open)} tone="blue" />
                    <Metric label="Brouillons" value={number(stats.draft)} tone="slate" />
                    <Metric label="Envoyées" value={number(stats.sent)} tone="amber" />
                    <Metric label="Montant potentiel" value={currency(stats.potentialAmount)} tone="green" />
                    <Metric label="Pipeline pondéré" value={currency(stats.weightedAmount)} 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]">Opportunités actives</h2>
                            <p className="mt-1 text-xs text-slate-500">{opportunities.total} dossier(s) en cours</p>
                        </div>
                        <form onSubmit={submit} className="flex gap-2">
                            <input
                                aria-label="Rechercher une opportunité"
                                value={search}
                                onChange={(event) => setSearch(event.target.value)}
                                placeholder="Offre ou 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-wide text-slate-500">
                                <tr>
                                    <th className="px-5 py-3 text-left">Opportunité</th>
                                    <th className="px-5 py-3 text-left">Entreprise</th>
                                    <th className="px-5 py-3 text-left">Statut</th>
                                    <th className="px-5 py-3 text-left">Montant</th>
                                    <th className="px-5 py-3 text-left">Probabilité</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {opportunities.data.length === 0 && (
                                    <tr><td colSpan={5} className="px-5 py-12 text-center text-slate-500">Aucune opportunité ouverte.</td></tr>
                                )}
                                {opportunities.data.map((opportunity) => (
                                    <tr key={opportunity.id} className="hover:bg-slate-50/70">
                                        <td className="px-5 py-4">
                                            <p className="font-semibold text-slate-900">{opportunity.title}</p>
                                            <p className="text-xs text-blue-700">{opportunity.reference}</p>
                                        </td>
                                        <td className="px-5 py-4">
                                            <Link href={route('companies.show', opportunity.company.id)} className="font-medium text-blue-700">
                                                {opportunity.company.name}
                                            </Link>
                                        </td>
                                        <td className="px-5 py-4"><Status value={opportunity.status} label={statusLabels[opportunity.status]} /></td>
                                        <td className="px-5 py-4 font-semibold">{currency(Number(opportunity.amount))}</td>
                                        <td className="px-5 py-4"><Progress value={opportunity.probability} /></td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>
            </div>
        </AuthenticatedLayout>
    );
}

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

    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 ${styles[tone]}`}>{value}</p></div>;
}

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

function Progress({ value }: { value: number }) {
    return <div className="w-28"><span className="text-xs font-semibold">{value}%</span><div className="mt-1 h-1.5 rounded bg-slate-100"><div className="h-1.5 rounded bg-blue-600" style={{ width: `${value}%` }} /></div></div>;
}

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

function currency(value: number) {
    return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(value);
}
