import { useForm } from '@inertiajs/react';
import { useEffect  } from 'react';
import type {FormEvent} from 'react';
import SupplierController from '@/actions/App/Http/Controllers/Admin/SupplierController';
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 { Textarea } from '@/components/ui/textarea';

export type SupplierFormValues = {
    id: number;
    code: string;
    name: string;
    contact_name: string | null;
    email: string | null;
    phone: string | null;
    address: string | null;
    payment_terms: string | null;
    is_active: boolean;
};

type Props = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    supplier?: SupplierFormValues | null;
};

export function SupplierFormModal({
    open,
    onOpenChange,
    supplier = null,
}: Props) {
    const isEditing = supplier !== null;

    const form = useForm({
        name: '',
        contact_name: '',
        email: '',
        phone: '',
        address: '',
        payment_terms: '',
        is_active: true,
    });

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

        form.setData({
            name: supplier?.name ?? '',
            contact_name: supplier?.contact_name ?? '',
            email: supplier?.email ?? '',
            phone: supplier?.phone ?? '',
            address: supplier?.address ?? '',
            payment_terms: supplier?.payment_terms ?? '',
            is_active: supplier?.is_active ?? true,
        });
        form.clearErrors();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, supplier]);

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

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

        if (isEditing && supplier) {
            form.put(SupplierController.update.url(supplier.id), options);

            return;
        }

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

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEditing
                            ? 'Modifier le fournisseur'
                            : 'Nouveau fournisseur'}
                    </DialogTitle>
                    <DialogDescription>
                        {isEditing
                            ? 'Mettre à jour les informations du fournisseur.'
                            : 'Le code sera généré automatiquement (ex. FRN-001).'}
                    </DialogDescription>
                </DialogHeader>

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

                    <div className="grid gap-2">
                        <Label htmlFor="supplier-name">Nom</Label>
                        <Input
                            id="supplier-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-4 sm:grid-cols-2">
                        <div className="grid gap-2">
                            <Label htmlFor="supplier-contact">
                                Personne de contact
                            </Label>
                            <Input
                                id="supplier-contact"
                                value={form.data.contact_name}
                                onChange={(event) =>
                                    form.setData(
                                        'contact_name',
                                        event.target.value,
                                    )
                                }
                            />
                            <InputError message={form.errors.contact_name} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="supplier-email">Email</Label>
                            <Input
                                id="supplier-email"
                                type="email"
                                value={form.data.email}
                                onChange={(event) =>
                                    form.setData('email', event.target.value)
                                }
                            />
                            <InputError message={form.errors.email} />
                        </div>
                    </div>

                    <div className="grid gap-4 sm:grid-cols-2">
                        <div className="grid gap-2">
                            <Label htmlFor="supplier-phone">Téléphone</Label>
                            <Input
                                id="supplier-phone"
                                value={form.data.phone}
                                onChange={(event) =>
                                    form.setData('phone', event.target.value)
                                }
                            />
                            <InputError message={form.errors.phone} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="supplier-terms">
                                Conditions de paiement
                            </Label>
                            <Input
                                id="supplier-terms"
                                placeholder="ex. 30 jours"
                                value={form.data.payment_terms}
                                onChange={(event) =>
                                    form.setData(
                                        'payment_terms',
                                        event.target.value,
                                    )
                                }
                            />
                            <InputError message={form.errors.payment_terms} />
                        </div>
                    </div>

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