import PrimaryButton from '@/Components/PrimaryButton';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types';
import { Company, Paginated } from '@/types/crm';
import { Head, Link, router } from '@inertiajs/react';
import { FormEventHandler, useState } from 'react';
import CompanyEnrichmentDrawer from './Partials/CompanyEnrichmentDrawer';

type Props = PageProps<{
    companies: Paginated<Company>;
    filters: {
        search: string;
        status: string;
        city: string;
        naf_code: string;
    };
    statusLabels: Record<string, string>;
    flash?: {
        success?: string | null;
        error?: string | null;
    };
}>;

export default function Index({ companies, filters, statusLabels, flash }: Props) {
    const [localFilters, setLocalFilters] = useState(filters);
    const [selectedCompany, setSelectedCompany] = useState<Company | null>(null);

    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        router.get(route('companies.index'), localFilters, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    const clearFilters = () => {
        const empty = {
            search: '',
            status: '',
            city: '',
            naf_code: '',
        };

        setLocalFilters(empty);
        router.get(route('companies.index'), empty, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    return (
        <AuthenticatedLayout
            header={
                <div className="flex items-center justify-between">
                    <h2 className="text-xl font-semibold leading-tight text-gray-800">
                        Entreprises CRM
                    </h2>
                    <div className="flex items-center gap-3">
                        <Link
                            href={route('companies.import.create')}
                            className="rounded-md border border-indigo-200 bg-indigo-50 px-3 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-100"
                        >
                            Import XLSX
                        </Link>
                        <Link href={route('companies.create')}>
                            <PrimaryButton>Nouvelle entreprise</PrimaryButton>
                        </Link>
                    </div>
                </div>
            }
        >
            <Head title="Entreprises" />

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

                    <section className="rounded-lg bg-white p-6 shadow-sm">
                        <form onSubmit={submit} className="grid gap-4 md:grid-cols-4">
                            <input
                                type="text"
                                value={localFilters.search}
                                onChange={(event) =>
                                    setLocalFilters((previous) => ({
                                        ...previous,
                                        search: event.target.value,
                                    }))
                                }
                                placeholder="Nom, ville, email, siret"
                                className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                            />
                            <select
                                value={localFilters.status}
                                onChange={(event) =>
                                    setLocalFilters((previous) => ({
                                        ...previous,
                                        status: event.target.value,
                                    }))
                                }
                                className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                            >
                                <option value="">Tous statuts</option>
                                {Object.entries(statusLabels).map(
                                    ([value, label]) => (
                                        <option key={value} value={value}>
                                            {label}
                                        </option>
                                    ),
                                )}
                            </select>
                            <input
                                type="text"
                                value={localFilters.city}
                                onChange={(event) =>
                                    setLocalFilters((previous) => ({
                                        ...previous,
                                        city: event.target.value,
                                    }))
                                }
                                placeholder="Ville"
                                className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                            />
                            <input
                                type="text"
                                value={localFilters.naf_code}
                                onChange={(event) =>
                                    setLocalFilters((previous) => ({
                                        ...previous,
                                        naf_code: event.target.value,
                                    }))
                                }
                                placeholder="Code NAF"
                                className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                            />

                            <div className="md:col-span-4 flex gap-3">
                                <PrimaryButton type="submit">Filtrer</PrimaryButton>
                                <button
                                    type="button"
                                    onClick={clearFilters}
                                    className="rounded-md border border-gray-300 px-4 py-2 text-xs font-semibold uppercase tracking-widest text-gray-700 hover:bg-gray-50"
                                >
                                    Reinitialiser
                                </button>
                            </div>
                        </form>
                    </section>

                    <section className="overflow-hidden rounded-lg bg-white shadow-sm">
                        <div className="overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200 text-sm">
                                <thead className="bg-gray-50">
                                    <tr>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Entreprise
                                        </th>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Localisation
                                        </th>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Contact
                                        </th>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Pipeline
                                        </th>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Suivi
                                        </th>
                                        <th className="px-4 py-3 text-left font-medium text-gray-600">
                                            Actions
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {companies.data.length === 0 && (
                                        <tr>
                                            <td
                                                colSpan={6}
                                                className="px-4 py-8 text-center text-gray-500"
                                            >
                                                Aucune entreprise trouvee.
                                            </td>
                                        </tr>
                                    )}

                                    {companies.data.map((company) => (
                                        <tr key={company.id}>
                                            <td className="px-4 py-3">
                                                <button
                                                    type="button"
                                                    onClick={() => setSelectedCompany(company)}
                                                    className="font-medium text-gray-900 hover:text-indigo-700 hover:underline"
                                                    aria-label={`Enrichir les coordonnees de ${company.name}`}
                                                >
                                                    {company.name}
                                                </button>
                                                <p className="text-xs text-gray-500">
                                                    {company.siret ?? 'SIRET non renseigne'}
                                                </p>
                                            </td>
                                            <td className="px-4 py-3 text-gray-700">
                                                {(company.postal_code ?? '') +
                                                    ' ' +
                                                    (company.city ?? '')}
                                            </td>
                                            <td className="px-4 py-3 text-gray-700">
                                                <p>{company.email ?? '-'}</p>
                                                <p className="text-xs text-gray-500">
                                                    {company.phone_primary ?? '-'}
                                                </p>
                                            </td>
                                            <td className="px-4 py-3 text-gray-700">
                                                {statusLabels[company.status] ??
                                                    company.status}
                                            </td>
                                            <td className="px-4 py-3 text-gray-700">
                                                <p>
                                                    Contacts: {company.contacts_count ?? 0}
                                                </p>
                                                <p className="text-xs text-gray-500">
                                                    Activites ouvertes:{' '}
                                                    {company.open_activities_count ??
                                                        0}
                                                </p>
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="flex gap-2">
                                                    <button
                                                        type="button"
                                                        onClick={() => setSelectedCompany(company)}
                                                        className="font-medium text-emerald-700 hover:text-emerald-600"
                                                    >
                                                        Enrichir
                                                    </button>
                                                    <Link
                                                        href={route(
                                                            'companies.show',
                                                            company.id,
                                                        )}
                                                        className="text-indigo-600 hover:text-indigo-500"
                                                    >
                                                        Voir
                                                    </Link>
                                                    <Link
                                                        href={route(
                                                            'companies.edit',
                                                            company.id,
                                                        )}
                                                        className="text-gray-700 hover:text-gray-600"
                                                    >
                                                        Modifier
                                                    </Link>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        <div className="flex flex-wrap gap-2 border-t border-gray-100 px-4 py-3">
                            {companies.links.map((link, index) => (
                                <button
                                    key={index}
                                    type="button"
                                    disabled={link.url === null}
                                    onClick={() =>
                                        link.url &&
                                        router.visit(link.url, {
                                            preserveState: true,
                                            preserveScroll: true,
                                        })
                                    }
                                    className={`rounded-md px-3 py-1 text-sm ${
                                        link.active
                                            ? 'bg-indigo-600 text-white'
                                            : 'bg-white text-gray-700 ring-1 ring-gray-200'
                                    } ${link.url === null ? 'opacity-40' : ''}`}
                                    dangerouslySetInnerHTML={{
                                        __html: link.label,
                                    }}
                                />
                            ))}
                        </div>
                    </section>
                </div>
            </div>

            {selectedCompany && (
                <CompanyEnrichmentDrawer
                    key={selectedCompany.id}
                    company={selectedCompany}
                    onClose={() => setSelectedCompany(null)}
                />
            )}
        </AuthenticatedLayout>
    );
}
