import { SelectField, TextInputField } from '@/components/form';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { useFlashToasts, showFlash, Flash } from '@/components/use-flash-toasts';
import { update as updateAlert } from '@/routes/alerts';
import { useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler } from 'react';
import type { Notification as Alert } from '@/types';

export interface AlertForm {
    user_id?: number | null;
    sender_id?: number | null;
    is_public: boolean;
    title: string;
    message: string;
    type: string;
    notifiable_type?: string | null;
    notifiable_id?: number | null;
    status: string;
}

interface UpdateAlertProps {
    open: boolean;
    setOpen: (value: boolean) => void;
    alert: Alert;
}

export default function UpdateAlert({ open, setOpen, alert }: UpdateAlertProps) {
    const { data, setData, put, processing, errors, reset } =
        useForm<AlertForm>({
            user_id: alert.user_id ?? null,
            sender_id: alert.sender_id ?? null,
            is_public: alert.is_public,
            title: alert.title,
            message: alert.message,
            type: alert.type,
            notifiable_type: alert.notifiable_type ?? '',
            notifiable_id: alert.notifiable_id ?? null,
            status: alert.status,
        });

    useFlashToasts({ errors });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        if (!isFormValid) return;
        put(updateAlert(alert.id).url, {
            onSuccess: (page) => {
                const flash = page.props.flash as Flash;
                showFlash(flash);
                reset();
                setOpen(false);
            },
            onError: () => {},
        });
    };

    const isFormValid = Boolean(data.title && data.message && data.type && data.status);

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="w-full max-w-[98vw] pb-4 sm:max-w-md">
                <DialogHeader>
                    <DialogTitle>Editar Alerta</DialogTitle>
                    <DialogDescription>
                        Modifica los campos para actualizar la alerta.
                    </DialogDescription>
                </DialogHeader>
                <form id="alert-update-form" onSubmit={submit}>
                    <div className="grid gap-4">
                        <TextInputField
                            id="title"
                            label="Título"
                            required
                            value={data.title}
                            onChange={(v) => setData('title', v)}
                            error={errors.title}
                        />
                        <TextInputField
                            id="message"
                            label="Mensaje"
                            required
                            value={data.message}
                            onChange={(v) => setData('message', v)}
                            error={errors.message}
                        />
                        <SelectField
                            id="type"
                            label="Tipo"
                            value={data.type}
                            onChange={(v) => setData('type', v)}
                            options={[
                                { value: '', label: 'Selecciona un tipo' },
                                { value: 'system', label: 'Sistema' },
                                { value: 'order', label: 'Orden' },
                                { value: 'event', label: 'Evento' },
                                { value: 'animal', label: 'Animal' },
                                { value: 'homologation', label: 'Homologación' },
                                { value: 'alert', label: 'Alerta' },
                                { value: 'reminder', label: 'Recordatorio' },
                            ]}
                            error={errors.type}
                        />
                        <SelectField
                            id="status"
                            label="Estado"
                            value={data.status}
                            onChange={(v) => setData('status', v)}
                            options={[
                                { value: 'active', label: 'Activo' },
                                { value: 'archived', label: 'Archivado' },
                                { value: 'deleted', label: 'Eliminado' },
                            ]}
                            error={errors.status}
                        />
                        <SelectField
                            id="is_public"
                            label="¿Es pública?"
                            value={data.is_public ? '1' : '0'}
                            onChange={(v) => setData('is_public', v === '1')}
                            options={[
                                { value: '0', label: 'No' },
                                { value: '1', label: 'Sí' },
                            ]}
                        />
                        {/* Puedes agregar campos para user_id, sender_id, notifiable_type, notifiable_id si lo necesitas */}
                    </div>
                </form>
                <DialogFooter>
                    <DialogClose asChild>
                        <Button variant="outline" type="button">
                            Cancelar
                        </Button>
                    </DialogClose>
                    <Button
                        type="submit"
                        form="alert-update-form"
                        disabled={processing || !isFormValid}
                    >
                        {processing && (
                            <LoaderCircle className="h-4 w-4 animate-spin" />
                        )}
                        Guardar Cambios
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
