import { useForm } from '@inertiajs/react';
import { useEffect, type FormEvent } from 'react';
import WarehouseController from '@/actions/App/Http/Controllers/Admin/WarehouseController';
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';

export type WarehouseFormValues = {
    id: number;
    code: string;
    name: string;
    address: string | null;
    manager_id: number | null;
    is_active: boolean;
};

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

type Props = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    warehouse?: WarehouseFormValues | null;
    users: UserOption[];
};

export function WarehouseFormModal({
    open,
    onOpenChange,
    warehouse = null,
    users,
}: Props) {
    const isEditing = warehouse !== null;

    const form = useForm({
        name: '',
        address: '',
        manager_id: '' as string,
        is_active: true,
    });

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

        form.setData({
            name: warehouse?.name ?? '',
            address: warehouse?.address ?? '',
            manager_id: warehouse?.manager_id
                ? String(warehouse.manager_id)
                : 'none',
            is_active: warehouse?.is_active ?? true,
        });
        form.clearErrors();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, warehouse]);

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

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

        form.transform((data) => ({
            name: data.name,
            address: data.address,
            manager_id:
                data.manager_id === 'none' || data.manager_id === ''
                    ? null
                    : Number(data.manager_id),
            is_active: data.is_active,
        }));

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

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

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEditing ? 'Modifier l’entrepôt' : 'Nouvel entrepôt'}
                    </DialogTitle>
                    <DialogDescription>
                        {isEditing
                            ? 'Mettre à jour les informations de l’entrepôt.'
                            : 'Le code sera généré automatiquement (ex. ENT-001).'}
                    </DialogDescription>
                </DialogHeader>

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

                    <div className="grid gap-2">
                        <Label htmlFor="warehouse-name">Nom</Label>
                        <Input
                            id="warehouse-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="warehouse-address">Adresse</Label>
                        <Textarea
                            id="warehouse-address"
                            rows={3}
                            value={form.data.address}
                            onChange={(event) =>
                                form.setData('address', event.target.value)
                            }
                        />
                        <InputError message={form.errors.address} />
                    </div>

                    <div className="grid gap-2">
                        <Label>Responsable</Label>
                        <Select
                            value={form.data.manager_id || 'none'}
                            onValueChange={(value) =>
                                form.setData('manager_id', value)
                            }
                        >
                            <SelectTrigger>
                                <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.manager_id} />
                    </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>
    );
}
