import InputError from '@/Components/InputError';
import InputLabel from '@/Components/InputLabel';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import { Company } from '@/types/crm';
import { useForm } from '@inertiajs/react';
import { FormEventHandler } from 'react';

type Props = {
    company: Company;
    onClose: () => void;
};

const sourceLabels: Record<string, string> = {
    official_website: 'Site officiel',
    google_business: 'Fiche Google',
    barreau_directory: 'Annuaire du barreau',
    manual: 'Verification manuelle',
};

export default function CompanyEnrichmentDrawer({ company, onClose }: Props) {
    const form = useForm({
        phone_primary: company.phone_primary ?? '',
        phone_mobile: company.phone_mobile ?? '',
        email: company.email ?? '',
        website: company.website ?? '',
        contact_enrichment_source:
            company.contact_enrichment_source ?? 'official_website',
        contact_enrichment_url: company.contact_enrichment_url ?? '',
        contact_enrichment_notes: company.contact_enrichment_notes ?? '',
    });

    const searchTerms = [
        company.name,
        company.branch_name,
        company.city,
        'avocat telephone email',
    ]
        .filter(Boolean)
        .join(' ');
    const mapTerms = [company.name, company.address_line1, company.city]
        .filter(Boolean)
        .join(' ');
    const googleSearchUrl = `https://www.google.com/search?q=${encodeURIComponent(searchTerms)}`;
    const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(mapTerms || searchTerms)}`;
    const officialWebsite = company.website
        ? /^https?:\/\//i.test(company.website)
            ? company.website
            : `https://${company.website}`
        : null;

    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        form.patch(route('companies.enrichment.update', company.id), {
            preserveScroll: true,
            onSuccess: onClose,
        });
    };

    return (
        <div
            className="fixed inset-0 z-50 flex justify-end bg-slate-950/40"
            role="presentation"
        >
            <button
                type="button"
                className="absolute inset-0 cursor-default"
                aria-label="Fermer le panneau"
                onClick={onClose}
            />
            <aside
                role="dialog"
                aria-modal="true"
                aria-labelledby="enrichment-title"
                className="relative flex h-full w-full max-w-xl flex-col overflow-y-auto bg-white shadow-2xl"
            >
                <header className="border-b border-slate-200 bg-[#062b5c] px-6 py-5 text-white">
                    <div className="flex items-start justify-between gap-4">
                        <div>
                            <p className="text-xs font-semibold uppercase tracking-wide text-blue-200">
                                Informations publiques
                            </p>
                            <h2 id="enrichment-title" className="mt-1 text-xl font-semibold">
                                Enrichir les coordonnees - {company.name}
                            </h2>
                            <p className="mt-1 text-sm text-blue-100">
                                {[company.postal_code, company.city]
                                    .filter(Boolean)
                                    .join(' ') || 'Localisation non renseignee'}
                            </p>
                        </div>
                        <button
                            type="button"
                            onClick={onClose}
                            className="rounded-md border border-white/30 px-3 py-1.5 text-sm hover:bg-white/10"
                            aria-label="Fermer"
                        >
                            X
                        </button>
                    </div>
                </header>

                <div className="space-y-6 p-6">
                    <section className="rounded-xl border border-blue-100 bg-blue-50 p-4">
                        <h3 className="text-sm font-semibold text-slate-900">
                            Retrouver les coordonnees
                        </h3>
                        <p className="mt-1 text-sm text-slate-600">
                            Consultez une source publique, puis enregistrez uniquement
                            les informations confirmees.
                        </p>
                        <div className="mt-4 flex flex-wrap gap-2">
                            <a
                                href={googleSearchUrl}
                                target="_blank"
                                rel="noreferrer"
                                className="rounded-lg bg-blue-700 px-3 py-2 text-sm font-medium text-white hover:bg-blue-800"
                            >
                                Rechercher sur Google
                            </a>
                            <a
                                href={googleMapsUrl}
                                target="_blank"
                                rel="noreferrer"
                                className="rounded-lg border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-800 hover:bg-blue-100"
                            >
                                Voir Google Maps
                            </a>
                            {officialWebsite && (
                                <a
                                    href={officialWebsite}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="rounded-lg border border-emerald-200 bg-white px-3 py-2 text-sm font-medium text-emerald-800 hover:bg-emerald-50"
                                >
                                    Site officiel
                                </a>
                            )}
                        </div>
                    </section>

                    {company.contact_enriched_at && (
                        <section className="rounded-xl border border-emerald-100 bg-emerald-50 p-4 text-sm text-emerald-900">
                            Derniere verification :{' '}
                            {new Date(company.contact_enriched_at).toLocaleString('fr-FR')}
                            {company.contact_enrichment_source &&
                                ` - ${sourceLabels[company.contact_enrichment_source] ?? company.contact_enrichment_source}`}
                        </section>
                    )}

                    <form className="space-y-4" onSubmit={submit}>
                        <h3 className="text-sm font-semibold text-slate-900">
                            Coordonnees verifiees
                        </h3>
                        <div className="grid gap-4 sm:grid-cols-2">
                            <div>
                                <InputLabel htmlFor="enrichment_phone_primary" value="Telephone principal" />
                                <TextInput
                                    id="enrichment_phone_primary"
                                    value={form.data.phone_primary}
                                    onChange={(event) =>
                                        form.setData('phone_primary', event.target.value)
                                    }
                                    className="mt-1 block w-full"
                                />
                                <InputError message={form.errors.phone_primary} className="mt-1" />
                            </div>
                            <div>
                                <InputLabel htmlFor="enrichment_phone_mobile" value="Mobile" />
                                <TextInput
                                    id="enrichment_phone_mobile"
                                    value={form.data.phone_mobile}
                                    onChange={(event) =>
                                        form.setData('phone_mobile', event.target.value)
                                    }
                                    className="mt-1 block w-full"
                                />
                                <InputError message={form.errors.phone_mobile} className="mt-1" />
                            </div>
                        </div>
                        <div>
                            <InputLabel htmlFor="enrichment_email" value="Email professionnel" />
                            <TextInput
                                id="enrichment_email"
                                type="email"
                                value={form.data.email}
                                onChange={(event) => form.setData('email', event.target.value)}
                                className="mt-1 block w-full"
                            />
                            <InputError message={form.errors.email} className="mt-1" />
                        </div>
                        <div>
                            <InputLabel htmlFor="enrichment_website" value="Site officiel" />
                            <TextInput
                                id="enrichment_website"
                                type="url"
                                value={form.data.website}
                                onChange={(event) => form.setData('website', event.target.value)}
                                placeholder="https://..."
                                className="mt-1 block w-full"
                            />
                            <InputError message={form.errors.website} className="mt-1" />
                        </div>
                        <div className="grid gap-4 sm:grid-cols-2">
                            <div>
                                <InputLabel htmlFor="enrichment_source" value="Source verifiee" />
                                <select
                                    id="enrichment_source"
                                    value={form.data.contact_enrichment_source}
                                    onChange={(event) =>
                                        form.setData('contact_enrichment_source', event.target.value)
                                    }
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                >
                                    {Object.entries(sourceLabels).map(([value, label]) => (
                                        <option key={value} value={value}>
                                            {label}
                                        </option>
                                    ))}
                                </select>
                                <InputError
                                    message={form.errors.contact_enrichment_source}
                                    className="mt-1"
                                />
                            </div>
                            <div>
                                <InputLabel htmlFor="enrichment_url" value="URL de preuve" />
                                <TextInput
                                    id="enrichment_url"
                                    type="url"
                                    value={form.data.contact_enrichment_url}
                                    onChange={(event) =>
                                        form.setData('contact_enrichment_url', event.target.value)
                                    }
                                    placeholder="https://..."
                                    className="mt-1 block w-full"
                                />
                                <InputError message={form.errors.contact_enrichment_url} className="mt-1" />
                            </div>
                        </div>
                        <div>
                            <InputLabel htmlFor="enrichment_notes" value="Notes de verification" />
                            <textarea
                                id="enrichment_notes"
                                value={form.data.contact_enrichment_notes}
                                onChange={(event) =>
                                    form.setData('contact_enrichment_notes', event.target.value)
                                }
                                rows={3}
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                placeholder="Ex. numero confirme sur la page Contact du cabinet."
                            />
                            <InputError message={form.errors.contact_enrichment_notes} className="mt-1" />
                        </div>
                        <div className="flex items-center justify-end gap-3 border-t border-slate-100 pt-4">
                            <button
                                type="button"
                                onClick={onClose}
                                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                            >
                                Annuler
                            </button>
                            <PrimaryButton disabled={form.processing}>
                                Enregistrer les coordonnees
                            </PrimaryButton>
                        </div>
                    </form>
                </div>
            </aside>
        </div>
    );
}
