import InputError from '@/Components/InputError';
import InputLabel from '@/Components/InputLabel';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types';
import { Company, CompanyActivity, CompanyContact } from '@/types/crm';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { FormEventHandler, useState } from 'react';
import CompanyEnrichmentDrawer from './Partials/CompanyEnrichmentDrawer';

type CompanyDetail = Company & {
    owner?: {
        id: number;
        name: string;
    };
    contacts: CompanyContact[];
    activities: CompanyActivity[];
};

type Props = PageProps<{
    company: CompanyDetail;
    statusLabels: Record<string, string>;
    activityTypeLabels: Record<string, string>;
    activityStatusLabels: Record<string, string>;
    flash?: {
        success?: string | null;
        error?: string | null;
    };
}>;

export default function Show({
    company,
    statusLabels,
    activityTypeLabels,
    activityStatusLabels,
    flash,
}: Props) {
    const [showEnrichment, setShowEnrichment] = useState(false);
    const contactForm = useForm({
        first_name: '',
        last_name: '',
        job_title: '',
        email: '',
        phone: '',
        mobile: '',
        is_primary: false,
        notes: '',
    });

    const activityForm = useForm({
        company_contact_id: '',
        type: 'task',
        status: 'open',
        subject: '',
        details: '',
        due_at: '',
    });

    const submitContact: FormEventHandler = (event) => {
        event.preventDefault();
        contactForm.post(route('companies.contacts.store', company.id), {
            preserveScroll: true,
            onSuccess: () => contactForm.reset(),
        });
    };

    const submitActivity: FormEventHandler = (event) => {
        event.preventDefault();
        activityForm.post(route('companies.activities.store', company.id), {
            preserveScroll: true,
            onSuccess: () =>
                activityForm.reset(
                    'company_contact_id',
                    'subject',
                    'details',
                    'due_at',
                ),
        });
    };

    return (
        <AuthenticatedLayout
            header={
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-xl font-semibold leading-tight text-gray-800">
                            {company.name}
                        </h2>
                        <p className="text-sm text-gray-500">
                            {statusLabels[company.status] ?? company.status}
                        </p>
                    </div>
                    <div className="flex items-center gap-3">
                        <button
                            type="button"
                            onClick={() => setShowEnrichment(true)}
                            className="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm font-medium text-emerald-700 hover:bg-emerald-100"
                        >
                            Enrichir les coordonnees
                        </button>
                        <Link
                            href={route('companies.edit', company.id)}
                            className="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                        >
                            Modifier
                        </Link>
                        <button
                            type="button"
                            onClick={() => {
                                if (
                                    window.confirm(
                                        'Supprimer cette entreprise et toutes ses donnees CRM ?',
                                    )
                                ) {
                                    router.delete(
                                        route('companies.destroy', company.id),
                                    );
                                }
                            }}
                            className="rounded-md border border-red-300 px-3 py-2 text-sm font-medium text-red-700 hover:bg-red-50"
                        >
                            Supprimer
                        </button>
                    </div>
                </div>
            }
        >
            <Head title={company.name} />

            <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">
                        <h3 className="mb-4 text-lg font-semibold text-gray-900">
                            Fiche entreprise
                        </h3>
                        <dl className="grid gap-4 md:grid-cols-3">
                            <Info label="Nom">{company.name}</Info>
                            <Info label="Cabinet">
                                {company.branch_name ?? '-'}
                            </Info>
                            <Info label="Barreau">
                                {company.bar_association ?? '-'}
                            </Info>
                            <Info label="Date de serment">
                                {formatDate(company.oath_date)}
                            </Info>
                            <Info label="SIRET">{company.siret ?? '-'}</Info>
                            <Info label="SIREN">{company.siren ?? '-'}</Info>
                            <Info label="Code NAF">{company.naf_code ?? '-'}</Info>
                            <Info label="Activite">
                                {company.activity_label ?? '-'}
                            </Info>
                            <Info label="Effectif">
                                {company.workforce_label ?? '-'}
                            </Info>
                            <Info label="Potentiel estime">
                                {company.estimated_potential
                                    ? `${company.estimated_potential} EUR`
                                    : '-'}
                            </Info>
                            <Info label="Email">{company.email ?? '-'}</Info>
                            <Info label="Tel principal">
                                {company.phone_primary ?? '-'}
                            </Info>
                            <Info label="Mobile">
                                {company.phone_mobile ?? '-'}
                            </Info>
                            <Info label="Adresse">
                                {[
                                    company.address_line1,
                                    company.address_line2,
                                    company.postal_code,
                                    company.city,
                                ]
                                    .filter(Boolean)
                                    .join(', ') || '-'}
                            </Info>
                            <Info label="Source">{company.source ?? '-'}</Info>
                            <Info label="Langue">
                                {company.languages ?? '-'}
                            </Info>
                            <Info label="Coordonnees verifiees">
                                {company.contact_enriched_at
                                    ? new Date(
                                          company.contact_enriched_at,
                                      ).toLocaleDateString('fr-FR')
                                    : '-'}
                            </Info>
                            <Info label="Prochain suivi">
                                {formatDate(company.next_follow_up_at)}
                            </Info>
                        </dl>

                        {company.notes && (
                            <div className="mt-4 rounded-md bg-gray-50 p-3 text-sm text-gray-700">
                                {company.notes}
                            </div>
                        )}
                    </section>

                    <div className="grid gap-6 lg:grid-cols-2">
                        <section className="rounded-lg bg-white p-6 shadow-sm">
                            <h3 className="mb-4 text-lg font-semibold text-gray-900">
                                Contacts
                            </h3>

                            <div className="space-y-3">
                                {company.contacts.length === 0 && (
                                    <p className="text-sm text-gray-500">
                                        Aucun contact enregistre.
                                    </p>
                                )}

                                {company.contacts.map((contact) => (
                                    <div
                                        key={contact.id}
                                        className="rounded-md border border-gray-200 p-3"
                                    >
                                        <div className="flex items-start justify-between gap-3">
                                            <div>
                                                <p className="font-medium text-gray-900">
                                                    {contact.full_name}
                                                    {contact.is_primary && (
                                                        <span className="ml-2 rounded bg-indigo-100 px-2 py-0.5 text-xs text-indigo-700">
                                                            principal
                                                        </span>
                                                    )}
                                                </p>
                                                <p className="text-sm text-gray-500">
                                                    {contact.job_title ??
                                                        'Fonction non renseignee'}
                                                </p>
                                                <p className="text-sm text-gray-600">
                                                    {contact.email ?? '-'} -{' '}
                                                    {contact.phone ??
                                                        contact.mobile ??
                                                        '-'}
                                                </p>
                                            </div>
                                            <button
                                                type="button"
                                                onClick={() => {
                                                    if (
                                                        window.confirm(
                                                            'Supprimer ce contact ?',
                                                        )
                                                    ) {
                                                        router.delete(
                                                            route(
                                                                'companies.contacts.destroy',
                                                                [
                                                                    company.id,
                                                                    contact.id,
                                                                ],
                                                            ),
                                                            {
                                                                preserveScroll:
                                                                    true,
                                                            },
                                                        );
                                                    }
                                                }}
                                                className="text-xs font-medium text-red-600 hover:text-red-500"
                                            >
                                                Supprimer
                                            </button>
                                        </div>
                                    </div>
                                ))}
                            </div>

                            <form onSubmit={submitContact} className="mt-6 space-y-3">
                                <h4 className="font-medium text-gray-900">
                                    Ajouter un contact
                                </h4>

                                <div className="grid gap-3 md:grid-cols-2">
                                    <div>
                                        <InputLabel htmlFor="contact_first_name" value="Prenom" />
                                        <TextInput
                                            id="contact_first_name"
                                            value={contactForm.data.first_name}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'first_name',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                        <InputError
                                            message={contactForm.errors.first_name}
                                            className="mt-1"
                                        />
                                    </div>
                                    <div>
                                        <InputLabel htmlFor="contact_last_name" value="Nom" />
                                        <TextInput
                                            id="contact_last_name"
                                            value={contactForm.data.last_name}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'last_name',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                        <InputError
                                            message={contactForm.errors.last_name}
                                            className="mt-1"
                                        />
                                    </div>
                                    <div>
                                        <InputLabel value="Fonction" />
                                        <TextInput
                                            value={contactForm.data.job_title}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'job_title',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                    </div>
                                    <div>
                                        <InputLabel htmlFor="contact_email" value="Email" />
                                        <TextInput
                                            id="contact_email"
                                            type="email"
                                            value={contactForm.data.email}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'email',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                    </div>
                                    <div>
                                        <InputLabel value="Telephone" />
                                        <TextInput
                                            value={contactForm.data.phone}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'phone',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                    </div>
                                    <div>
                                        <InputLabel value="Mobile" />
                                        <TextInput
                                            value={contactForm.data.mobile}
                                            onChange={(event) =>
                                                contactForm.setData(
                                                    'mobile',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                    </div>
                                </div>

                                <label className="flex items-center gap-2 text-sm text-gray-700">
                                    <input
                                        type="checkbox"
                                        checked={contactForm.data.is_primary}
                                        onChange={(event) =>
                                            contactForm.setData(
                                                'is_primary',
                                                event.target.checked,
                                            )
                                        }
                                    />
                                    Contact principal
                                </label>

                                <PrimaryButton disabled={contactForm.processing}>
                                    Ajouter
                                </PrimaryButton>
                            </form>
                        </section>

                        <section className="rounded-lg bg-white p-6 shadow-sm">
                            <h3 className="mb-4 text-lg font-semibold text-gray-900">
                                Activites et suivi
                            </h3>

                            <div className="space-y-3">
                                {company.activities.length === 0 && (
                                    <p className="text-sm text-gray-500">
                                        Aucune activite enregistree.
                                    </p>
                                )}

                                {company.activities.map((activity) => (
                                    <div
                                        key={activity.id}
                                        className="rounded-md border border-gray-200 p-3"
                                    >
                                        <div className="flex items-start justify-between gap-3">
                                            <div>
                                                <p className="font-medium text-gray-900">
                                                    {activity.subject}
                                                </p>
                                                <p className="text-sm text-gray-500">
                                                    {activityTypeLabels[
                                                        activity.type
                                                    ] ?? activity.type}{' '}
                                                    -{' '}
                                                    {activityStatusLabels[
                                                        activity.status
                                                    ] ?? activity.status}
                                                </p>
                                                <p className="text-xs text-gray-500">
                                                    Echeance:{' '}
                                                    {formatDate(activity.due_at)}
                                                </p>
                                                {activity.details && (
                                                    <p className="mt-1 text-sm text-gray-700">
                                                        {activity.details}
                                                    </p>
                                                )}
                                            </div>

                                            <div className="flex flex-col gap-2 text-xs">
                                                {activity.status !== 'done' && (
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            router.patch(
                                                                route(
                                                                    'companies.activities.update',
                                                                    [
                                                                        company.id,
                                                                        activity.id,
                                                                    ],
                                                                ),
                                                                {
                                                                    status: 'done',
                                                                },
                                                                {
                                                                    preserveScroll:
                                                                        true,
                                                                },
                                                            )
                                                        }
                                                        className="font-medium text-emerald-700 hover:text-emerald-600"
                                                    >
                                                        Marquer done
                                                    </button>
                                                )}
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        if (
                                                            window.confirm(
                                                                'Supprimer cette activite ?',
                                                            )
                                                        ) {
                                                            router.delete(
                                                                route(
                                                                    'companies.activities.destroy',
                                                                    [
                                                                        company.id,
                                                                        activity.id,
                                                                    ],
                                                                ),
                                                                {
                                                                    preserveScroll:
                                                                        true,
                                                                },
                                                            );
                                                        }
                                                    }}
                                                    className="font-medium text-red-600 hover:text-red-500"
                                                >
                                                    Supprimer
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>

                            <form onSubmit={submitActivity} className="mt-6 space-y-3">
                                <h4 className="font-medium text-gray-900">
                                    Ajouter une activite
                                </h4>

                                <div className="grid gap-3 md:grid-cols-2">
                                    <div>
                                        <InputLabel htmlFor="activity_type" value="Type" />
                                        <select
                                            id="activity_type"
                                            value={activityForm.data.type}
                                            onChange={(event) =>
                                                activityForm.setData(
                                                    'type',
                                                    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(activityTypeLabels).map(
                                                ([value, label]) => (
                                                    <option key={value} value={value}>
                                                        {label}
                                                    </option>
                                                ),
                                            )}
                                        </select>
                                    </div>

                                    <div>
                                        <InputLabel value="Statut" />
                                        <select
                                            value={activityForm.data.status}
                                            onChange={(event) =>
                                                activityForm.setData(
                                                    'status',
                                                    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(
                                                activityStatusLabels,
                                            ).map(([value, label]) => (
                                                <option key={value} value={value}>
                                                    {label}
                                                </option>
                                            ))}
                                        </select>
                                    </div>

                                    <div className="md:col-span-2">
                                        <InputLabel htmlFor="activity_subject" value="Sujet" />
                                        <TextInput
                                            id="activity_subject"
                                            value={activityForm.data.subject}
                                            onChange={(event) =>
                                                activityForm.setData(
                                                    'subject',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                        <InputError
                                            message={activityForm.errors.subject}
                                            className="mt-1"
                                        />
                                    </div>

                                    <div>
                                        <InputLabel value="Contact lie" />
                                        <select
                                            value={activityForm.data.company_contact_id}
                                            onChange={(event) =>
                                                activityForm.setData(
                                                    'company_contact_id',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                        >
                                            <option value="">Aucun</option>
                                            {company.contacts.map((contact) => (
                                                <option
                                                    key={contact.id}
                                                    value={contact.id}
                                                >
                                                    {contact.full_name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>

                                    <div>
                                        <InputLabel htmlFor="activity_due_at" value="Echeance" />
                                        <TextInput
                                            id="activity_due_at"
                                            type="date"
                                            value={activityForm.data.due_at}
                                            onChange={(event) =>
                                                activityForm.setData(
                                                    'due_at',
                                                    event.target.value,
                                                )
                                            }
                                            className="mt-1 block w-full"
                                        />
                                    </div>
                                </div>

                                <div>
                                    <InputLabel value="Details" />
                                    <textarea
                                        value={activityForm.data.details}
                                        onChange={(event) =>
                                            activityForm.setData(
                                                'details',
                                                event.target.value,
                                            )
                                        }
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                        rows={3}
                                    />
                                </div>

                                <PrimaryButton disabled={activityForm.processing}>
                                    Ajouter l'activite
                                </PrimaryButton>
                            </form>
                        </section>
                    </div>
                </div>
            </div>

            {showEnrichment && (
                <CompanyEnrichmentDrawer
                    company={company}
                    onClose={() => setShowEnrichment(false)}
                />
            )}
        </AuthenticatedLayout>
    );
}

function Info({ label, children }: { label: string; children: string }) {
    return (
        <div>
            <dt className="text-xs uppercase tracking-wide text-gray-500">
                {label}
            </dt>
            <dd className="mt-1 text-sm text-gray-900">{children}</dd>
        </div>
    );
}

function formatDate(value: string | null): string {
    if (!value) {
        return '-';
    }

    return new Date(value).toLocaleDateString('fr-FR');
}
