import { useForm } from '@inertiajs/react';
import { ArrowLeft, ArrowRight, Check } from 'lucide-react';
import {
    Children,
    cloneElement,
    isValidElement,
    useMemo,
    useState,
} from 'react';
import type { KeyboardEvent, ReactNode } from 'react';
import type {
    ContractTypeOption,
    DepartmentOption,
    JobPositionOption,
    ManagerOption,
    SiteOption,
    UserOption,
} from './employee-form';
import EmployeeController from '@/actions/App/Http/Controllers/Admin/EmployeeController';
import InputError from '@/components/input-error';
import { SearchableSelect } from '@/components/searchable-select';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { cn } from '@/lib/utils';

const STEPS = [
    { id: 'identity', title: 'Identité' },
    { id: 'role', title: 'Poste' },
    { id: 'contract', title: 'Contrat' },
    { id: 'access', title: 'Accès' },
] as const;

const STEP_COPY = [
    {
        title: 'Qui est cette personne ?',
        description:
            'État civil, pièce d’identité, adresse et situation personnelle.',
    },
    {
        title: 'Quel est son rôle ?',
        description: 'Poste, organisation et conditions de travail.',
    },
    {
        title: 'Quel contrat ouvre le dossier ?',
        description: 'Le premier contrat sera le contrat courant.',
    },
    {
        title: 'Finaliser',
        description: 'Lier un compte, un manager, puis créer.',
    },
] as const;

type StepIndex = 0 | 1 | 2 | 3;

type StepField =
    | 'civility'
    | 'first_name'
    | 'last_name'
    | 'birth_name'
    | 'email'
    | 'personal_email'
    | 'phone'
    | 'work_phone'
    | 'birth_date'
    | 'birth_place'
    | 'nationality'
    | 'cnps_number'
    | 'cmu_number'
    | 'id_document_type'
    | 'id_document_number'
    | 'id_document_issued_on'
    | 'id_document_expires_on'
    | 'residence_permit_number'
    | 'residence_permit_expires_on'
    | 'work_permit_number'
    | 'work_permit_expires_on'
    | 'address'
    | 'postal_code'
    | 'city'
    | 'quartier'
    | 'commune'
    | 'country'
    | 'marital_status'
    | 'dependent_children_count'
    | 'emergency_contact_name'
    | 'emergency_contact_relationship'
    | 'emergency_contact_phone'
    | 'job_title'
    | 'job_position_id'
    | 'professional_category'
    | 'classification'
    | 'work_time'
    | 'weekly_hours'
    | 'department_id'
    | 'site_id'
    | 'hire_date'
    | 'seniority_date'
    | 'probation_end_date'
    | 'contract_type'
    | 'contract_start'
    | 'contract_end'
    | 'user_id'
    | 'manager_id'
    | 'is_active';

const STEP_FIELDS: StepField[][] = [
    [
        'civility',
        'first_name',
        'last_name',
        'birth_name',
        'email',
        'personal_email',
        'phone',
        'work_phone',
        'birth_date',
        'birth_place',
        'nationality',
        'cnps_number',
        'cmu_number',
        'id_document_type',
        'id_document_number',
        'id_document_issued_on',
        'id_document_expires_on',
        'residence_permit_number',
        'residence_permit_expires_on',
        'work_permit_number',
        'work_permit_expires_on',
        'address',
        'postal_code',
        'city',
        'quartier',
        'commune',
        'country',
        'marital_status',
        'dependent_children_count',
        'emergency_contact_name',
        'emergency_contact_relationship',
        'emergency_contact_phone',
    ],
    [
        'job_title',
        'job_position_id',
        'department_id',
        'site_id',
        'professional_category',
        'classification',
        'work_time',
        'weekly_hours',
        'hire_date',
        'seniority_date',
        'probation_end_date',
    ],
    ['contract_type', 'contract_start', 'contract_end'],
    ['user_id', 'manager_id', 'is_active'],
];

type Props = {
    contractTypes: ContractTypeOption[];
    civilities: ContractTypeOption[];
    maritalStatuses: ContractTypeOption[];
    workTimes: ContractTypeOption[];
    professionalCategories: ContractTypeOption[];
    idDocumentTypes: ContractTypeOption[];
    users: UserOption[];
    managers: ManagerOption[];
    departments: DepartmentOption[];
    sites: SiteOption[];
    jobPositions: JobPositionOption[];
};

function Field({
    children,
    className,
}: {
    children: ReactNode;
    className?: string;
}) {
    const items = Children.toArray(children);
    const invalid = items.some(
        (child) =>
            isValidElement<{ message?: string }>(child) &&
            child.type === InputError &&
            Boolean(child.props.message),
    );

    return (
        <div
            className={cn(
                'relative grid content-start gap-2',
                '**:data-[slot=input-error]:absolute **:data-[slot=input-error]:top-full **:data-[slot=input-error]:left-0 **:data-[slot=input-error]:z-10 **:data-[slot=input-error]:mt-1 **:data-[slot=input-error]:max-w-full **:data-[slot=input-error]:text-xs **:data-[slot=input-error]:leading-tight',
                className,
            )}
        >
            {items.map((child, index) => {
                if (!isValidElement(child)) {
                    return child;
                }

                if (child.type === Input || child.type === Textarea) {
                    return cloneElement(child, {
                        key: child.key ?? index,
                        'aria-invalid': invalid || undefined,
                    } as never);
                }

                if (child.type === SearchableSelect) {
                    return cloneElement(child, {
                        key: child.key ?? index,
                        invalid,
                    } as never);
                }

                return child;
            })}
        </div>
    );
}

function digitsOnlyPhone(value: string): string {
    return value.replace(/[^\d+\s().-]/g, '');
}

function CreateSection({
    title,
    children,
}: {
    title: string;
    children: ReactNode;
}) {
    return (
        <div className="space-y-5">
            <p className="text-xs font-medium tracking-[0.12em] text-muted-foreground uppercase">
                {title}
            </p>
            <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3">
                {children}
            </div>
        </div>
    );
}

function SectionRule() {
    return <hr className="border-0 border-t border-border" />;
}

export function EmployeeCreateForm({
    contractTypes,
    civilities,
    maritalStatuses,
    workTimes,
    professionalCategories,
    idDocumentTypes,
    users,
    managers,
    departments,
    sites,
    jobPositions,
}: Props) {
    const [step, setStep] = useState<StepIndex>(0);
    const [stepErrors, setStepErrors] = useState<
        Partial<Record<StepField, string>>
    >({});

    const form = useForm({
        civility: 'none',
        first_name: '',
        last_name: '',
        birth_name: '',
        email: '',
        personal_email: '',
        phone: '',
        work_phone: '',
        birth_date: '',
        birth_place: '',
        nationality: '',
        cnps_number: '',
        cmu_number: '',
        id_document_type: 'none',
        id_document_number: '',
        id_document_issued_on: '',
        id_document_expires_on: '',
        residence_permit_number: '',
        residence_permit_expires_on: '',
        work_permit_number: '',
        work_permit_expires_on: '',
        address: '',
        postal_code: '',
        city: '',
        quartier: '',
        commune: '',
        country: '',
        marital_status: 'none',
        dependent_children_count: '',
        emergency_contact_name: '',
        emergency_contact_relationship: '',
        emergency_contact_phone: '',
        job_title: '',
        job_position_id: 'none',
        professional_category: 'none',
        classification: '',
        work_time: 'none',
        weekly_hours: '',
        department_id: 'none',
        site_id: 'none',
        hire_date: '',
        seniority_date: '',
        probation_end_date: '',
        contract_type: contractTypes[0]?.value ?? 'cdi',
        contract_start: '',
        contract_end: '',
        user_id: 'none',
        manager_id: 'none',
        is_active: true,
    });

    const contractLabel = useMemo(
        () =>
            contractTypes.find((type) => type.value === form.data.contract_type)
                ?.label ?? form.data.contract_type,
        [contractTypes, form.data.contract_type],
    );

    const userOptions = useMemo(
        () =>
            users.map((user) => ({
                value: String(user.id),
                label: user.name,
            })),
        [users],
    );

    const managerOptions = useMemo(
        () =>
            managers.map((manager) => ({
                value: String(manager.user_id),
                label: `${manager.full_name} (${manager.code})`,
            })),
        [managers],
    );

    const departmentOptions = useMemo(
        () =>
            departments.map((department) => ({
                value: String(department.id),
                label: department.name,
            })),
        [departments],
    );

    const siteOptions = useMemo(
        () =>
            sites.map((site) => ({
                value: String(site.id),
                label: site.name,
            })),
        [sites],
    );

    const jobPositionOptions = useMemo(
        () =>
            jobPositions.map((position) => ({
                value: String(position.id),
                label: position.name,
            })),
        [jobPositions],
    );

    const selectedUser = users.find(
        (user) => String(user.id) === form.data.user_id,
    );
    const selectedManager = managers.find(
        (manager) => String(manager.user_id) === form.data.manager_id,
    );
    const selectedDepartment = departments.find(
        (department) => String(department.id) === form.data.department_id,
    );

    function clearFieldError(field: StepField) {
        setStepErrors((current) => {
            if (!current[field]) {
                return current;
            }

            const next = { ...current };
            delete next[field];

            return next;
        });
    }

    function validateStep(current: StepIndex): boolean {
        const errors: Partial<Record<StepField, string>> = {};

        if (current === 0) {
            if (!form.data.first_name.trim()) {
                errors.first_name = 'Le prénom est obligatoire.';
            }

            if (!form.data.last_name.trim()) {
                errors.last_name = 'Le nom est obligatoire.';
            }

            if (
                form.data.email.trim() &&
                !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.data.email.trim())
            ) {
                errors.email = 'Adresse email invalide.';
            }
        }

        if (current === 2) {
            if (!form.data.contract_type) {
                errors.contract_type = 'Le type de contrat est obligatoire.';
            }

            if (
                form.data.contract_start &&
                form.data.contract_end &&
                form.data.contract_end < form.data.contract_start
            ) {
                errors.contract_end =
                    'La date de fin doit être postérieure ou égale au début.';
            }
        }

        setStepErrors(errors);

        return Object.keys(errors).length === 0;
    }

    function goNext() {
        if (!validateStep(step)) {
            return;
        }

        setStep(
            (current) => Math.min(current + 1, STEPS.length - 1) as StepIndex,
        );
    }

    function goBack() {
        setStepErrors({});
        setStep((current) => Math.max(current - 1, 0) as StepIndex);
    }

    function stepHasServerError(index: number): boolean {
        return STEP_FIELDS[index].some((field) => Boolean(form.errors[field]));
    }

    function createEmployee() {
        const identityOk = validateStep(0);

        if (!identityOk) {
            setStep(0);

            return;
        }

        const contractOk = validateStep(2);

        if (!contractOk) {
            setStep(2);

            return;
        }

        form.transform((data) => ({
            civility: data.civility === 'none' ? null : data.civility,
            first_name: data.first_name,
            last_name: data.last_name,
            birth_name: data.birth_name || null,
            email: data.email || null,
            personal_email: data.personal_email || null,
            phone: data.phone || null,
            work_phone: data.work_phone || null,
            birth_date: data.birth_date || null,
            birth_place: data.birth_place || null,
            nationality: data.nationality || null,
            cnps_number: data.cnps_number || null,
            cmu_number: data.cmu_number || null,
            id_document_type:
                data.id_document_type === 'none' ? null : data.id_document_type,
            id_document_number: data.id_document_number || null,
            id_document_issued_on: data.id_document_issued_on || null,
            id_document_expires_on: data.id_document_expires_on || null,
            residence_permit_number: data.residence_permit_number || null,
            residence_permit_expires_on:
                data.residence_permit_expires_on || null,
            work_permit_number: data.work_permit_number || null,
            work_permit_expires_on: data.work_permit_expires_on || null,
            address: data.address || null,
            postal_code: data.postal_code || null,
            city: data.city || null,
            quartier: data.quartier || null,
            commune: data.commune || null,
            country: data.country || null,
            marital_status:
                data.marital_status === 'none' ? null : data.marital_status,
            dependent_children_count:
                data.dependent_children_count === ''
                    ? null
                    : Number(data.dependent_children_count),
            emergency_contact_name: data.emergency_contact_name || null,
            emergency_contact_relationship:
                data.emergency_contact_relationship || null,
            emergency_contact_phone: data.emergency_contact_phone || null,
            job_title: data.job_title || null,
            job_position_id:
                data.job_position_id === 'none'
                    ? null
                    : Number(data.job_position_id),
            professional_category:
                data.professional_category === 'none'
                    ? null
                    : data.professional_category,
            classification: data.classification || null,
            work_time: data.work_time === 'none' ? null : data.work_time,
            weekly_hours:
                data.weekly_hours === '' ? null : Number(data.weekly_hours),
            department_id:
                data.department_id === 'none'
                    ? null
                    : Number(data.department_id),
            site_id: data.site_id === 'none' ? null : Number(data.site_id),
            hire_date: data.hire_date || null,
            seniority_date: data.seniority_date || null,
            probation_end_date: data.probation_end_date || null,
            contract_type: data.contract_type,
            contract_start: data.contract_start || null,
            contract_end: data.contract_end || null,
            user_id: data.user_id === 'none' ? null : Number(data.user_id),
            manager_id:
                data.manager_id === 'none' ? null : Number(data.manager_id),
            is_active: data.is_active,
        }));

        form.post(EmployeeController.store.url(), {
            onError: (errors) => {
                const firstErrorStep = STEP_FIELDS.findIndex((fields) =>
                    fields.some((field) => Boolean(errors[field])),
                );

                if (firstErrorStep >= 0) {
                    setStep(firstErrorStep as StepIndex);
                }
            },
        });
    }

    function handleFormKeyDown(event: KeyboardEvent<HTMLFormElement>) {
        if (event.key !== 'Enter') {
            return;
        }

        const target = event.target as HTMLElement;

        if (target.tagName === 'TEXTAREA' || target.isContentEditable) {
            return;
        }

        // Empêche la soumission implicite (ex. Entrée dans un champ date).
        event.preventDefault();

        if (step < STEPS.length - 1) {
            goNext();
        }
    }

    return (
        <form
            onSubmit={(event) => event.preventDefault()}
            onKeyDown={handleFormKeyDown}
            className="space-y-10"
        >
            {' '}
            <nav aria-label="Progression" className="space-y-4">
                <div className="relative">
                    <div
                        aria-hidden
                        className="absolute top-3.5 right-3 left-3 h-px bg-border"
                    />
                    <div
                        aria-hidden
                        className="absolute top-3.5 left-3 h-px bg-foreground transition-all duration-500 ease-out"
                        style={{
                            width:
                                step === 0
                                    ? '0%'
                                    : `calc(${(step / (STEPS.length - 1)) * 100}% - 0.75rem)`,
                        }}
                    />
                    <ol className="relative z-10 flex justify-between">
                        {STEPS.map((item, index) => {
                            const isCurrent = index === step;
                            const isDone = index < step;
                            const hasError = stepHasServerError(index);
                            const canNavigate = index <= step;

                            return (
                                <li key={item.id}>
                                    <button
                                        type="button"
                                        disabled={!canNavigate}
                                        onClick={() => {
                                            if (!canNavigate) {
                                                return;
                                            }

                                            setStepErrors({});
                                            setStep(index as StepIndex);
                                        }}
                                        className={cn(
                                            'flex flex-col items-center gap-2.5 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/40',
                                            !canNavigate && 'cursor-default',
                                        )}
                                    >
                                        <span
                                            className={cn(
                                                'flex size-7 items-center justify-center rounded-full text-[11px] font-medium transition-colors',
                                                isCurrent &&
                                                    'bg-foreground text-background ring-4 ring-background',
                                                isDone &&
                                                    !isCurrent &&
                                                    'bg-primary text-primary-foreground ring-4 ring-background',
                                                !isCurrent &&
                                                    !isDone &&
                                                    'bg-muted text-muted-foreground ring-4 ring-background',
                                                hasError &&
                                                    'ring-4 ring-destructive/30',
                                            )}
                                        >
                                            {isDone ? (
                                                <Check
                                                    className="size-3.5"
                                                    strokeWidth={2.5}
                                                />
                                            ) : (
                                                index + 1
                                            )}
                                        </span>
                                        <span
                                            className={cn(
                                                'text-[11px] tracking-wide',
                                                isCurrent
                                                    ? 'font-medium text-foreground'
                                                    : 'text-muted-foreground',
                                            )}
                                        >
                                            {item.title}
                                        </span>
                                    </button>
                                </li>
                            );
                        })}
                    </ol>
                </div>
            </nav>
            <section
                key={step}
                className="animate-in space-y-8 duration-300 fade-in-0 slide-in-from-bottom-1"
            >
                <div className="space-y-1.5">
                    <p className="text-xs font-medium tracking-[0.12em] text-muted-foreground uppercase">
                        Étape {step + 1} sur {STEPS.length}
                    </p>
                    <h2 className="text-lg font-semibold tracking-tight">
                        {STEP_COPY[step].title}
                    </h2>
                    <p className="text-sm leading-relaxed text-muted-foreground">
                        {STEP_COPY[step].description}
                    </p>
                </div>

                {step === 0 && (
                    <div className="space-y-8">
                        <CreateSection title="État civil">
                            <Field>
                                <Label>Civilité</Label>
                                <SearchableSelect
                                    options={civilities}
                                    value={form.data.civility}
                                    onChange={(value) => {
                                        form.setData('civility', value);
                                        clearFieldError('civility');
                                    }}
                                    placeholder="Choisir…"
                                    noneLabel="Non renseignée"
                                />
                                <InputError
                                    message={
                                        stepErrors.civility ||
                                        form.errors.civility
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="last_name">Nom</Label>
                                <Input
                                    id="last_name"
                                    value={form.data.last_name}
                                    onChange={(e) => {
                                        form.setData(
                                            'last_name',
                                            e.target.value,
                                        );
                                        clearFieldError('last_name');
                                    }}
                                    autoFocus
                                    autoComplete="family-name"
                                />
                                <InputError
                                    message={
                                        stepErrors.last_name ||
                                        form.errors.last_name
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="first_name">Prénom</Label>
                                <Input
                                    id="first_name"
                                    value={form.data.first_name}
                                    onChange={(e) => {
                                        form.setData(
                                            'first_name',
                                            e.target.value,
                                        );
                                        clearFieldError('first_name');
                                    }}
                                    autoComplete="given-name"
                                />
                                <InputError
                                    message={
                                        stepErrors.first_name ||
                                        form.errors.first_name
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="birth_name">
                                    Nom de naissance
                                </Label>
                                <Input
                                    id="birth_name"
                                    value={form.data.birth_name}
                                    onChange={(e) => {
                                        form.setData(
                                            'birth_name',
                                            e.target.value,
                                        );
                                        clearFieldError('birth_name');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.birth_name ||
                                        form.errors.birth_name
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="birth_date">
                                    Date de naissance
                                </Label>
                                <Input
                                    id="birth_date"
                                    type="date"
                                    value={form.data.birth_date}
                                    onChange={(e) => {
                                        form.setData(
                                            'birth_date',
                                            e.target.value,
                                        );
                                        clearFieldError('birth_date');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.birth_date ||
                                        form.errors.birth_date
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="birth_place">
                                    Lieu de naissance
                                </Label>
                                <Input
                                    id="birth_place"
                                    value={form.data.birth_place}
                                    onChange={(e) => {
                                        form.setData(
                                            'birth_place',
                                            e.target.value,
                                        );
                                        clearFieldError('birth_place');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.birth_place ||
                                        form.errors.birth_place
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="nationality">Nationalité</Label>
                                <Input
                                    id="nationality"
                                    value={form.data.nationality}
                                    onChange={(e) => {
                                        form.setData(
                                            'nationality',
                                            e.target.value,
                                        );
                                        clearFieldError('nationality');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.nationality ||
                                        form.errors.nationality
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="cnps_number">N° CNPS</Label>
                                <Input
                                    id="cnps_number"
                                    value={form.data.cnps_number}
                                    onChange={(e) => {
                                        form.setData(
                                            'cnps_number',
                                            e.target.value,
                                        );
                                        clearFieldError('cnps_number');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.cnps_number ||
                                        form.errors.cnps_number
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="cmu_number">N° CMU</Label>
                                <Input
                                    id="cmu_number"
                                    value={form.data.cmu_number}
                                    onChange={(e) => {
                                        form.setData(
                                            'cmu_number',
                                            e.target.value,
                                        );
                                        clearFieldError('cmu_number');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.cmu_number ||
                                        form.errors.cmu_number
                                    }
                                />
                            </Field>
                            <Field>
                                <Label>Situation familiale</Label>
                                <SearchableSelect
                                    options={maritalStatuses}
                                    value={form.data.marital_status}
                                    onChange={(value) => {
                                        form.setData('marital_status', value);
                                        clearFieldError('marital_status');
                                    }}
                                    placeholder="Choisir…"
                                    noneLabel="Non renseignée"
                                />
                                <InputError
                                    message={
                                        stepErrors.marital_status ||
                                        form.errors.marital_status
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="dependent_children_count">
                                    Enfants à charge
                                </Label>
                                <Input
                                    id="dependent_children_count"
                                    type="number"
                                    min={0}
                                    max={20}
                                    value={form.data.dependent_children_count}
                                    onChange={(e) => {
                                        form.setData(
                                            'dependent_children_count',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'dependent_children_count',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.dependent_children_count ||
                                        form.errors.dependent_children_count
                                    }
                                />
                            </Field>
                        </CreateSection>

                        <SectionRule />

                        <CreateSection title="Pièce d’identité">
                            <Field>
                                <Label>Type de pièce</Label>
                                <SearchableSelect
                                    options={idDocumentTypes}
                                    value={form.data.id_document_type}
                                    onChange={(value) => {
                                        form.setData('id_document_type', value);
                                        clearFieldError('id_document_type');
                                    }}
                                    placeholder="Choisir…"
                                    noneLabel="Non renseigné"
                                />
                                <InputError
                                    message={
                                        stepErrors.id_document_type ||
                                        form.errors.id_document_type
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="id_document_number">
                                    Numéro
                                </Label>
                                <Input
                                    id="id_document_number"
                                    value={form.data.id_document_number}
                                    onChange={(e) => {
                                        form.setData(
                                            'id_document_number',
                                            e.target.value,
                                        );
                                        clearFieldError('id_document_number');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.id_document_number ||
                                        form.errors.id_document_number
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="id_document_issued_on">
                                    Date de délivrance
                                </Label>
                                <Input
                                    id="id_document_issued_on"
                                    type="date"
                                    value={form.data.id_document_issued_on}
                                    onChange={(e) => {
                                        form.setData(
                                            'id_document_issued_on',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'id_document_issued_on',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.id_document_issued_on ||
                                        form.errors.id_document_issued_on
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="id_document_expires_on">
                                    Date d’expiration
                                </Label>
                                <Input
                                    id="id_document_expires_on"
                                    type="date"
                                    value={form.data.id_document_expires_on}
                                    onChange={(e) => {
                                        form.setData(
                                            'id_document_expires_on',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'id_document_expires_on',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.id_document_expires_on ||
                                        form.errors.id_document_expires_on
                                    }
                                />
                            </Field>
                        </CreateSection>

                        <SectionRule />

                        <CreateSection title="Titre de séjour et travail">
                            <Field>
                                <Label htmlFor="residence_permit_number">
                                    N° titre de séjour
                                </Label>
                                <Input
                                    id="residence_permit_number"
                                    value={form.data.residence_permit_number}
                                    onChange={(e) => {
                                        form.setData(
                                            'residence_permit_number',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'residence_permit_number',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.residence_permit_number ||
                                        form.errors.residence_permit_number
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="residence_permit_expires_on">
                                    Expiration du titre de séjour
                                </Label>
                                <Input
                                    id="residence_permit_expires_on"
                                    type="date"
                                    value={
                                        form.data.residence_permit_expires_on
                                    }
                                    onChange={(e) => {
                                        form.setData(
                                            'residence_permit_expires_on',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'residence_permit_expires_on',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.residence_permit_expires_on ||
                                        form.errors.residence_permit_expires_on
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="work_permit_number">
                                    N° autorisation de travail
                                </Label>
                                <Input
                                    id="work_permit_number"
                                    value={form.data.work_permit_number}
                                    onChange={(e) => {
                                        form.setData(
                                            'work_permit_number',
                                            e.target.value,
                                        );
                                        clearFieldError('work_permit_number');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.work_permit_number ||
                                        form.errors.work_permit_number
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="work_permit_expires_on">
                                    Expiration de l’autorisation de travail
                                </Label>
                                <Input
                                    id="work_permit_expires_on"
                                    type="date"
                                    value={form.data.work_permit_expires_on}
                                    onChange={(e) => {
                                        form.setData(
                                            'work_permit_expires_on',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'work_permit_expires_on',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.work_permit_expires_on ||
                                        form.errors.work_permit_expires_on
                                    }
                                />
                            </Field>
                        </CreateSection>

                        <SectionRule />

                        <CreateSection title="Coordonnées">
                            <Field>
                                <Label htmlFor="email">
                                    Email professionnel
                                </Label>
                                <Input
                                    id="email"
                                    type="email"
                                    value={form.data.email}
                                    onChange={(e) => {
                                        form.setData('email', e.target.value);
                                        clearFieldError('email');
                                    }}
                                    autoComplete="email"
                                    placeholder="prenom.nom@entreprise.com"
                                />
                                <InputError
                                    message={
                                        stepErrors.email || form.errors.email
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="personal_email">
                                    Email personnel
                                </Label>
                                <Input
                                    id="personal_email"
                                    type="email"
                                    value={form.data.personal_email}
                                    onChange={(e) => {
                                        form.setData(
                                            'personal_email',
                                            e.target.value,
                                        );
                                        clearFieldError('personal_email');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.personal_email ||
                                        form.errors.personal_email
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="phone">
                                    Téléphone personnel
                                </Label>
                                <Input
                                    id="phone"
                                    type="tel"
                                    inputMode="tel"
                                    value={form.data.phone}
                                    onChange={(e) => {
                                        form.setData(
                                            'phone',
                                            digitsOnlyPhone(e.target.value),
                                        );
                                        clearFieldError('phone');
                                    }}
                                    autoComplete="tel"
                                />
                                <InputError
                                    message={
                                        stepErrors.phone || form.errors.phone
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="work_phone">
                                    Téléphone professionnel
                                </Label>
                                <Input
                                    id="work_phone"
                                    type="tel"
                                    inputMode="tel"
                                    value={form.data.work_phone}
                                    onChange={(e) => {
                                        form.setData(
                                            'work_phone',
                                            digitsOnlyPhone(e.target.value),
                                        );
                                        clearFieldError('work_phone');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.work_phone ||
                                        form.errors.work_phone
                                    }
                                />
                            </Field>
                            <Field className="sm:col-span-2 lg:col-span-3">
                                <Label htmlFor="address">Adresse</Label>
                                <Textarea
                                    id="address"
                                    value={form.data.address}
                                    onChange={(e) => {
                                        form.setData('address', e.target.value);
                                        clearFieldError('address');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.address ||
                                        form.errors.address
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="postal_code">Code postal</Label>
                                <Input
                                    id="postal_code"
                                    value={form.data.postal_code}
                                    onChange={(e) => {
                                        form.setData(
                                            'postal_code',
                                            e.target.value,
                                        );
                                        clearFieldError('postal_code');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.postal_code ||
                                        form.errors.postal_code
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="quartier">Quartier</Label>
                                <Input
                                    id="quartier"
                                    value={form.data.quartier}
                                    onChange={(e) => {
                                        form.setData(
                                            'quartier',
                                            e.target.value,
                                        );
                                        clearFieldError('quartier');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.quartier ||
                                        form.errors.quartier
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="commune">Commune</Label>
                                <Input
                                    id="commune"
                                    value={form.data.commune}
                                    onChange={(e) => {
                                        form.setData('commune', e.target.value);
                                        clearFieldError('commune');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.commune ||
                                        form.errors.commune
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="city">Ville</Label>
                                <Input
                                    id="city"
                                    value={form.data.city}
                                    onChange={(e) => {
                                        form.setData('city', e.target.value);
                                        clearFieldError('city');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.city || form.errors.city
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="country">Pays</Label>
                                <Input
                                    id="country"
                                    value={form.data.country}
                                    onChange={(e) => {
                                        form.setData('country', e.target.value);
                                        clearFieldError('country');
                                    }}
                                    placeholder="Côte d’Ivoire"
                                />
                                <InputError
                                    message={
                                        stepErrors.country ||
                                        form.errors.country
                                    }
                                />
                            </Field>
                        </CreateSection>

                        <SectionRule />

                        <CreateSection title="Contact d’urgence">
                            <Field>
                                <Label htmlFor="emergency_contact_name">
                                    Nom
                                </Label>
                                <Input
                                    id="emergency_contact_name"
                                    value={form.data.emergency_contact_name}
                                    onChange={(e) => {
                                        form.setData(
                                            'emergency_contact_name',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'emergency_contact_name',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.emergency_contact_name ||
                                        form.errors.emergency_contact_name
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="emergency_contact_relationship">
                                    Lien
                                </Label>
                                <Input
                                    id="emergency_contact_relationship"
                                    value={
                                        form.data.emergency_contact_relationship
                                    }
                                    onChange={(e) => {
                                        form.setData(
                                            'emergency_contact_relationship',
                                            e.target.value,
                                        );
                                        clearFieldError(
                                            'emergency_contact_relationship',
                                        );
                                    }}
                                    placeholder="Conjoint, parent…"
                                />
                                <InputError
                                    message={
                                        stepErrors.emergency_contact_relationship ||
                                        form.errors
                                            .emergency_contact_relationship
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="emergency_contact_phone">
                                    Téléphone
                                </Label>
                                <Input
                                    id="emergency_contact_phone"
                                    type="tel"
                                    inputMode="tel"
                                    value={form.data.emergency_contact_phone}
                                    onChange={(e) => {
                                        form.setData(
                                            'emergency_contact_phone',
                                            digitsOnlyPhone(e.target.value),
                                        );
                                        clearFieldError(
                                            'emergency_contact_phone',
                                        );
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.emergency_contact_phone ||
                                        form.errors.emergency_contact_phone
                                    }
                                />
                            </Field>
                        </CreateSection>
                    </div>
                )}

                {step === 1 && (
                    <div className="space-y-8">
                        <CreateSection title="Poste">
                            <Field>
                                <Label>Poste (référentiel)</Label>
                                <SearchableSelect
                                    options={jobPositionOptions}
                                    value={form.data.job_position_id}
                                    onChange={(value) => {
                                        const position = jobPositions.find(
                                            (item) => String(item.id) === value,
                                        );
                                        const categoryIsEmpty =
                                            form.data.professional_category ===
                                                'none' ||
                                            form.data.professional_category ===
                                                '';
                                        const classificationIsEmpty =
                                            form.data.classification === '';

                                        form.setData({
                                            ...form.data,
                                            job_position_id: value,
                                            professional_category:
                                                categoryIsEmpty &&
                                                position?.professional_category
                                                    ? position.professional_category
                                                    : form.data
                                                          .professional_category,
                                            classification:
                                                classificationIsEmpty &&
                                                position?.classification
                                                    ? position.classification
                                                    : form.data.classification,
                                        });
                                        clearFieldError('job_position_id');
                                    }}
                                    placeholder="Choisir un poste…"
                                    searchPlaceholder="Nom du poste…"
                                    noneLabel="Aucun"
                                />
                                <InputError
                                    message={
                                        stepErrors.job_position_id ??
                                        form.errors.job_position_id
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="job_title">
                                    Intitulé du poste
                                </Label>
                                <Input
                                    id="job_title"
                                    value={form.data.job_title}
                                    onChange={(e) =>
                                        form.setData(
                                            'job_title',
                                            e.target.value,
                                        )
                                    }
                                    autoFocus
                                    placeholder="Ex. Responsable commercial"
                                />
                                <InputError message={form.errors.job_title} />
                            </Field>
                            <Field>
                                <Label>Service</Label>
                                <SearchableSelect
                                    options={departmentOptions}
                                    value={form.data.department_id}
                                    onChange={(value) => {
                                        form.setData('department_id', value);
                                        clearFieldError('department_id');
                                    }}
                                    placeholder="Choisir un département…"
                                    searchPlaceholder="Nom du département…"
                                    noneLabel="Aucun"
                                />
                                <InputError
                                    message={
                                        stepErrors.department_id ??
                                        form.errors.department_id
                                    }
                                />
                            </Field>
                            <Field>
                                <Label>Site</Label>
                                <SearchableSelect
                                    options={siteOptions}
                                    value={form.data.site_id}
                                    onChange={(value) => {
                                        form.setData('site_id', value);
                                        clearFieldError('site_id');
                                    }}
                                    placeholder="Choisir un site…"
                                    searchPlaceholder="Nom du site…"
                                    noneLabel="Aucun"
                                />
                                <InputError
                                    message={
                                        stepErrors.site_id ||
                                        form.errors.site_id
                                    }
                                />
                            </Field>
                            <Field>
                                <Label>Statut</Label>
                                <SearchableSelect
                                    options={professionalCategories}
                                    value={form.data.professional_category}
                                    onChange={(value) => {
                                        form.setData(
                                            'professional_category',
                                            value,
                                        );
                                        clearFieldError(
                                            'professional_category',
                                        );
                                    }}
                                    placeholder="Choisir…"
                                    noneLabel="Non renseigné"
                                />
                                <InputError
                                    message={
                                        stepErrors.professional_category ||
                                        form.errors.professional_category
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="classification">
                                    Catégorie / échelon
                                </Label>
                                <Input
                                    id="classification"
                                    value={form.data.classification}
                                    onChange={(e) => {
                                        form.setData(
                                            'classification',
                                            e.target.value,
                                        );
                                        clearFieldError('classification');
                                    }}
                                    placeholder="Ex. Catégorie 3, échelon 2"
                                />
                                <InputError
                                    message={
                                        stepErrors.classification ||
                                        form.errors.classification
                                    }
                                />
                            </Field>
                        </CreateSection>

                        <SectionRule />

                        <CreateSection title="Conditions de travail">
                            <Field>
                                <Label>Temps de travail</Label>
                                <SearchableSelect
                                    options={workTimes}
                                    value={form.data.work_time}
                                    onChange={(value) => {
                                        form.setData('work_time', value);
                                        clearFieldError('work_time');
                                    }}
                                    placeholder="Choisir…"
                                    noneLabel="Non renseigné"
                                />
                                <InputError
                                    message={
                                        stepErrors.work_time ||
                                        form.errors.work_time
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="weekly_hours">
                                    Heures hebdomadaires
                                </Label>
                                <Input
                                    id="weekly_hours"
                                    type="number"
                                    min={0}
                                    max={60}
                                    step="0.5"
                                    value={form.data.weekly_hours}
                                    onChange={(e) => {
                                        form.setData(
                                            'weekly_hours',
                                            e.target.value,
                                        );
                                        clearFieldError('weekly_hours');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.weekly_hours ||
                                        form.errors.weekly_hours
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="hire_date">
                                    Date d’embauche
                                </Label>
                                <Input
                                    id="hire_date"
                                    type="date"
                                    value={form.data.hire_date}
                                    onChange={(e) =>
                                        form.setData(
                                            'hire_date',
                                            e.target.value,
                                        )
                                    }
                                />
                                <InputError message={form.errors.hire_date} />
                            </Field>
                            <Field>
                                <Label htmlFor="seniority_date">
                                    Date d’ancienneté
                                </Label>
                                <Input
                                    id="seniority_date"
                                    type="date"
                                    value={form.data.seniority_date}
                                    onChange={(e) => {
                                        form.setData(
                                            'seniority_date',
                                            e.target.value,
                                        );
                                        clearFieldError('seniority_date');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.seniority_date ||
                                        form.errors.seniority_date
                                    }
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="probation_end_date">
                                    Fin de période d’essai
                                </Label>
                                <Input
                                    id="probation_end_date"
                                    type="date"
                                    value={form.data.probation_end_date}
                                    onChange={(e) => {
                                        form.setData(
                                            'probation_end_date',
                                            e.target.value,
                                        );
                                        clearFieldError('probation_end_date');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.probation_end_date ||
                                        form.errors.probation_end_date
                                    }
                                />
                            </Field>
                        </CreateSection>
                    </div>
                )}

                {step === 2 && (
                    <div className="space-y-6">
                        <Field>
                            <Label>Type de contrat</Label>
                            <div
                                role="radiogroup"
                                aria-label="Type de contrat"
                                className="grid grid-cols-2 gap-2 sm:grid-cols-4"
                            >
                                {contractTypes.map((type) => {
                                    const selected =
                                        form.data.contract_type === type.value;

                                    return (
                                        <button
                                            key={type.value}
                                            type="button"
                                            role="radio"
                                            aria-checked={selected}
                                            onClick={() => {
                                                form.setData(
                                                    'contract_type',
                                                    type.value,
                                                );
                                                clearFieldError(
                                                    'contract_type',
                                                );
                                            }}
                                            className={cn(
                                                'rounded-md border px-3 py-2.5 text-sm transition-colors',
                                                selected
                                                    ? 'border-foreground bg-foreground text-background'
                                                    : 'border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground',
                                            )}
                                        >
                                            {type.label}
                                        </button>
                                    );
                                })}
                            </div>
                            <InputError
                                message={
                                    stepErrors.contract_type ||
                                    form.errors.contract_type
                                }
                            />
                        </Field>

                        <SectionRule />

                        <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3">
                            <Field>
                                <Label htmlFor="contract_start">
                                    Début{' '}
                                    <span className="font-normal text-muted-foreground">
                                        (date d’embauche si vide)
                                    </span>
                                </Label>
                                <Input
                                    id="contract_start"
                                    type="date"
                                    value={form.data.contract_start}
                                    onChange={(e) => {
                                        form.setData(
                                            'contract_start',
                                            e.target.value,
                                        );
                                        clearFieldError('contract_end');
                                    }}
                                />
                                <InputError
                                    message={form.errors.contract_start}
                                />
                            </Field>
                            <Field>
                                <Label htmlFor="contract_end">
                                    Fin{' '}
                                    <span className="font-normal text-muted-foreground">
                                        (optionnel)
                                    </span>
                                </Label>
                                <Input
                                    id="contract_end"
                                    type="date"
                                    value={form.data.contract_end}
                                    onChange={(e) => {
                                        form.setData(
                                            'contract_end',
                                            e.target.value,
                                        );
                                        clearFieldError('contract_end');
                                    }}
                                />
                                <InputError
                                    message={
                                        stepErrors.contract_end ||
                                        form.errors.contract_end
                                    }
                                />
                            </Field>
                        </div>
                    </div>
                )}

                {step === 3 && (
                    <div className="space-y-8">
                        <dl className="divide-y divide-border border-y">
                            {[
                                {
                                    label: 'Collaborateur',
                                    value:
                                        [
                                            form.data.last_name,
                                            form.data.first_name,
                                        ]
                                            .filter(Boolean)
                                            .join(' ') || '—',
                                },
                                {
                                    label: 'Poste',
                                    value:
                                        [
                                            form.data.job_title || null,
                                            selectedDepartment?.name || null,
                                        ]
                                            .filter(Boolean)
                                            .join(' · ') || '—',
                                },
                                {
                                    label: 'Contrat',
                                    value: [
                                        contractLabel,
                                        form.data.contract_start
                                            ? `dès ${form.data.contract_start}`
                                            : null,
                                    ]
                                        .filter(Boolean)
                                        .join(' · '),
                                },
                                {
                                    label: 'Embauche',
                                    value: form.data.hire_date || '—',
                                },
                            ].map((row) => (
                                <div
                                    key={row.label}
                                    className="flex items-baseline justify-between gap-6 py-3.5"
                                >
                                    <dt className="shrink-0 text-sm text-muted-foreground">
                                        {row.label}
                                    </dt>
                                    <dd className="text-right text-sm font-medium tracking-tight">
                                        {row.value}
                                    </dd>
                                </div>
                            ))}
                        </dl>

                        <SectionRule />

                        <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3">
                            <Field>
                                <Label>Compte utilisateur</Label>
                                <SearchableSelect
                                    options={userOptions}
                                    value={form.data.user_id}
                                    onChange={(value) =>
                                        form.setData('user_id', value)
                                    }
                                    placeholder="Rechercher un compte…"
                                    searchPlaceholder="Nom du compte…"
                                    noneLabel="Non lié"
                                />
                                <InputError message={form.errors.user_id} />
                            </Field>
                            <Field>
                                <Label>Manager</Label>
                                <SearchableSelect
                                    options={managerOptions}
                                    value={form.data.manager_id}
                                    onChange={(value) =>
                                        form.setData('manager_id', value)
                                    }
                                    placeholder="Rechercher un manager…"
                                    searchPlaceholder="Nom du manager…"
                                    noneLabel="Aucun"
                                />
                                <InputError message={form.errors.manager_id} />
                            </Field>
                        </div>

                        <label
                            htmlFor="is_active"
                            className="flex cursor-pointer items-start gap-3 rounded-md border px-4 py-3.5 transition-colors hover:bg-muted/40"
                        >
                            <Checkbox
                                id="is_active"
                                className="mt-0.5"
                                checked={form.data.is_active}
                                onCheckedChange={(checked) =>
                                    form.setData('is_active', checked === true)
                                }
                            />
                            <span className="space-y-0.5">
                                <span className="block text-sm font-medium">
                                    Activer dès la création
                                </span>
                                <span className="block text-xs leading-relaxed text-muted-foreground">
                                    {selectedUser
                                        ? `Compte lié : ${selectedUser.name}`
                                        : 'Le collaborateur apparaîtra dans les effectifs actifs.'}
                                    {selectedManager
                                        ? ` · Manager : ${selectedManager.full_name}`
                                        : ''}
                                </span>
                            </span>
                        </label>
                    </div>
                )}
            </section>
            <div className="flex items-center justify-between gap-3 border-t border-border pt-6">
                {step > 0 ? (
                    <Button
                        type="button"
                        variant="ghost"
                        onClick={goBack}
                        className="text-muted-foreground"
                    >
                        <ArrowLeft />
                        Retour
                    </Button>
                ) : (
                    <span />
                )}

                {step < STEPS.length - 1 ? (
                    <Button type="button" onClick={goNext}>
                        Continuer
                        <ArrowRight />
                    </Button>
                ) : (
                    <Button
                        type="button"
                        onClick={createEmployee}
                        disabled={form.processing}
                    >
                        Créer le collaborateur
                    </Button>
                )}
            </div>
        </form>
    );
}
