import { useForm } from '@inertiajs/react';
import { useEffect } from 'react';
import type { FormEvent } from 'react';
import JobPositionController from '@/actions/App/Http/Controllers/Admin/JobPositionController';
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 {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

export type JobPositionFormValues = {
    id: number;
    code: string;
    name: string;
    professional_category: string | null;
    professional_category_label: string | null;
    classification: string | null;
    convention_collective: string | null;
    is_active: boolean;
};

type Option = { value: string; label: string };

const CONVENTION_COLLECTIVE_SUGGESTIONS = [
    'Convention collective interprofessionnelle',
    'Commerce',
    'Banques et établissements financiers',
    'Bâtiment et travaux publics',
    'Hôtellerie-restauration',
    'Transports terrestres',
    'Pétrole',
    'Assurances',
    'Télécommunications',
    'Enseignement privé',
];

type Props = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    jobPosition?: JobPositionFormValues | null;
    professionalCategories: Option[];
};

export function JobPositionFormModal({
    open,
    onOpenChange,
    jobPosition = null,
    professionalCategories,
}: Props) {
    const isEditing = jobPosition !== null;

    const form = useForm({
        name: '',
        professional_category: 'none',
        classification: '',
        convention_collective: '',
        is_active: true,
    });

    useEffect(() => {
        if (!open) {
            return;
        }

        form.setData({
            name: jobPosition?.name ?? '',
            professional_category: jobPosition?.professional_category ?? 'none',
            classification: jobPosition?.classification ?? '',
            convention_collective: jobPosition?.convention_collective ?? '',
            is_active: jobPosition?.is_active ?? true,
        });
        form.clearErrors();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, jobPosition]);

    function submit(event: FormEvent) {
        event.preventDefault();

        form.transform((data) => ({
            name: data.name,
            professional_category:
                data.professional_category === 'none'
                    ? null
                    : data.professional_category,
            classification: data.classification || null,
            convention_collective: data.convention_collective || null,
            is_active: data.is_active,
        }));

        const options = {
            preserveScroll: true,
            onSuccess: () => onOpenChange(false),
        };

        if (isEditing && jobPosition) {
            form.put(JobPositionController.update.url(jobPosition.id), options);

            return;
        }

        form.post(JobPositionController.store.url(), options);
    }

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEditing ? 'Modifier le poste' : 'Nouveau poste'}
                    </DialogTitle>
                    <DialogDescription>
                        {isEditing
                            ? 'Mettre à jour le référentiel de poste.'
                            : 'Le code sera généré automatiquement (ex. POST-001).'}
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-4">
                    {isEditing && jobPosition && (
                        <div className="grid gap-2">
                            <Label>Code</Label>
                            <Input
                                value={jobPosition.code}
                                disabled
                                readOnly
                                className="font-mono"
                            />
                        </div>
                    )}

                    <div className="grid gap-2">
                        <Label htmlFor="name">Nom</Label>
                        <Input
                            id="name"
                            value={form.data.name}
                            onChange={(e) =>
                                form.setData('name', e.target.value)
                            }
                            autoFocus
                        />
                        <InputError message={form.errors.name} />
                    </div>

                    <div className="grid gap-2">
                        <Label>Catégorie professionnelle</Label>
                        <SearchableSelect
                            options={professionalCategories}
                            value={form.data.professional_category}
                            onChange={(value) =>
                                form.setData('professional_category', value)
                            }
                            placeholder="Choisir…"
                            noneLabel="Non renseignée"
                        />
                        <InputError
                            message={form.errors.professional_category}
                        />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="classification">
                            Catégorie / échelon
                        </Label>
                        <Input
                            id="classification"
                            value={form.data.classification}
                            onChange={(e) =>
                                form.setData('classification', e.target.value)
                            }
                            placeholder="Ex. Catégorie 3, échelon 2"
                        />
                        <InputError message={form.errors.classification} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="convention_collective">
                            Convention collective
                        </Label>
                        <Input
                            id="convention_collective"
                            list="convention-collective-suggestions"
                            value={form.data.convention_collective}
                            onChange={(e) =>
                                form.setData(
                                    'convention_collective',
                                    e.target.value,
                                )
                            }
                            placeholder="Texte libre, suggestions indicatives"
                        />
                        <datalist id="convention-collective-suggestions">
                            {CONVENTION_COLLECTIVE_SUGGESTIONS.map(
                                (suggestion) => (
                                    <option
                                        key={suggestion}
                                        value={suggestion}
                                    />
                                ),
                            )}
                        </datalist>
                        <InputError
                            message={form.errors.convention_collective}
                        />
                    </div>

                    <label className="flex items-center gap-2">
                        <Checkbox
                            checked={form.data.is_active}
                            onCheckedChange={(checked) =>
                                form.setData('is_active', checked === true)
                            }
                        />
                        <span className="text-sm">Poste actif</span>
                    </label>

                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => onOpenChange(false)}
                        >
                            Annuler
                        </Button>
                        <Button type="submit" disabled={form.processing}>
                            {isEditing ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
