import { useForm } from '@inertiajs/react';
import { useEffect, type FormEvent } from 'react';
import ServiceController from '@/actions/App/Http/Controllers/Admin/ServiceController';
import InputError from '@/components/input-error';
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';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useCompanyCurrency } from '@/hooks/use-company-currency';

export type CategoryOption = {
    id: number;
    name: string;
};

export type UnitOption = {
    value: string;
    label: string;
};

export type UserOption = {
    id: number;
    name: string;
};

export type ServiceFormValues = {
    id: number;
    code: string;
    name: string;
    category_id: number;
    responsible_id: number | null;
    description: string | null;
    price: string | number;
    unit: string;
    is_active: boolean;
};

type Props = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    categories: CategoryOption[];
    units: UnitOption[];
    users: UserOption[];
    service?: ServiceFormValues | null;
};

export function ServiceFormModal({
    open,
    onOpenChange,
    categories,
    units,
    users,
    service = null,
}: Props) {
    const isEditing = service !== null;
    const { symbol: currencySymbol } = useCompanyCurrency();

    const form = useForm({
        name: '',
        category_id: '',
        responsible_id: '',
        description: '',
        price: '',
        unit: units[0]?.value ?? '',
        is_active: true,
    });

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

        form.setData({
            name: service?.name ?? '',
            category_id: service ? String(service.category_id) : '',
            responsible_id: service?.responsible_id
                ? String(service.responsible_id)
                : '',
            description: service?.description ?? '',
            price: service ? String(service.price) : '',
            unit: service?.unit ?? (units[0]?.value ?? ''),
            is_active: service?.is_active ?? true,
        });
        form.clearErrors();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, service]);

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

        form.transform((data) => ({
            ...data,
            responsible_id:
                data.responsible_id === 'none' || data.responsible_id === ''
                    ? null
                    : Number(data.responsible_id),
        }));

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

        if (isEditing && service) {
            form.put(ServiceController.update.url(service.id), options);
            return;
        }

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

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEditing
                            ? 'Modifier la prestation'
                            : 'Nouvelle prestation'}
                    </DialogTitle>
                    <DialogDescription>
                        {isEditing
                            ? 'Mettre à jour les informations de la prestation.'
                            : 'Le code sera généré automatiquement (ex. SRV-001).'}
                    </DialogDescription>
                </DialogHeader>

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

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

                    <div className="grid gap-2">
                        <Label htmlFor="service-category">
                            Pôle d’activité
                        </Label>
                        <Select
                            value={form.data.category_id || undefined}
                            onValueChange={(value) =>
                                form.setData('category_id', value)
                            }
                        >
                            <SelectTrigger
                                id="service-category"
                                className="w-full"
                            >
                                <SelectValue placeholder="Choisir un pôle d’activité…" />
                            </SelectTrigger>
                            <SelectContent>
                                {categories.map((category) => (
                                    <SelectItem
                                        key={category.id}
                                        value={String(category.id)}
                                    >
                                        {category.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={form.errors.category_id} />
                    </div>

                    <div className="grid gap-2">
                        <Label>Responsable</Label>
                        <Select
                            value={form.data.responsible_id || 'none'}
                            onValueChange={(value) =>
                                form.setData('responsible_id', value)
                            }
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Sélectionner" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="none">Aucun</SelectItem>
                                {users.map((user) => (
                                    <SelectItem
                                        key={user.id}
                                        value={String(user.id)}
                                    >
                                        {user.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={form.errors.responsible_id} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="service-description">
                            Description
                        </Label>
                        <Textarea
                            id="service-description"
                            rows={3}
                            value={form.data.description}
                            onChange={(event) =>
                                form.setData('description', event.target.value)
                            }
                        />
                        <InputError message={form.errors.description} />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="service-price">
                                Prix ({currencySymbol})
                            </Label>
                            <Input
                                id="service-price"
                                type="number"
                                step="0.01"
                                min="0"
                                value={form.data.price}
                                onChange={(event) =>
                                    form.setData('price', event.target.value)
                                }
                                required
                            />
                            <InputError message={form.errors.price} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="service-unit">Unité</Label>
                            <Select
                                value={form.data.unit || undefined}
                                onValueChange={(value) =>
                                    form.setData('unit', value)
                                }
                            >
                                <SelectTrigger
                                    id="service-unit"
                                    className="w-full"
                                >
                                    <SelectValue placeholder="Choisir une unité…" />
                                </SelectTrigger>
                                <SelectContent>
                                    {units.map((unit) => (
                                        <SelectItem
                                            key={unit.value}
                                            value={unit.value}
                                        >
                                            {unit.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={form.errors.unit} />
                        </div>
                    </div>

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

                    <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>
    );
}
