import { SelectField, TextInputField, ComboBoxField } from '@/components/form';
import { ViewMaps } from '@/components/form/ViewMaps';
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 { store as storeNotification } from '@/routes/alerts';
import { useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler } from 'react';

export interface NotificationForm {
    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;
    location?: string;
    dog_id?: string;
    litter_id?: string;
}

interface CreateNotificationProps {
    open: boolean;
    setOpen: (value: boolean) => void;
}

export default function CreateNotification({ open, setOpen }: CreateNotificationProps) {
    const { data, setData, post, processing, errors, reset } =
        useForm<NotificationForm>({
            user_id: null,
            sender_id: null,
            is_public: false,
            title: '',
            message: '',
            type: '',
            notifiable_type: '',
            notifiable_id: null,
            status: 'active',
            location: '',
            dog_id: '',
            litter_id: '',
        });

    useFlashToasts({ errors });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        if (!isFormValid) return;
        post(storeNotification().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);

    // Opciones de ejemplo, reemplaza con datos reales
    const dogOptions = [
        { value: '1', label: 'Bully Max' },
        { value: '2', label: 'Bully Queen' },
        { value: '3', label: 'Bully King' },
    ];
    const litterOptions = [
        { value: 'a', label: 'Camada A' },
        { value: 'b', label: 'Camada B' },
        { value: 'c', label: 'Camada C' },
    ];

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="w-full max-w-[98vw] pb-4 sm:max-w-md">
                <DialogHeader>
                    <DialogTitle>Crear Notificación</DialogTitle>
                    <DialogDescription>
                        Completa los campos para registrar una nueva notificación.
                    </DialogDescription>
                </DialogHeader>
                <form id="notification-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: 'Alerta de robo', label: 'Alerta de robo' },
                                { value: 'Alerta de extravío', label: 'Alerta de extravío' },
                                { value: 'Alerta de fallecimiento', label: 'Alerta de fallecimiento' },
                                { value: 'Alerta de celo', label: 'Alerta de celo' },
                                { value: 'Alerta de camadas disponibles', label: 'Alerta de camadas disponibles' },
                                { value: 'Alerta de padrillo disponible', label: 'Alerta de padrillo disponible' },
                            ]}
                            error={errors.type}
                        />
                        {/* Mostrar ubicación y mapa solo para robo/extravío */}
                        {(data.type === 'Alerta de robo' || data.type === 'Alerta de extravío') && (
                            <>
                                <TextInputField
                                    id="location"
                                    label="Ubicación"
                                    required
                                    value={data.location}
                                    onChange={(v) => setData('location', v)}
                                    error={errors.location}
                                    placeholder="Ingresa la ubicación manualmente"
                                />
                                <div className="col-span-1">
                                    <ViewMaps
                                        id="location-search"
                                        label="Búsqueda avanzada de ubicación"
                                        value={data.location}
                                        onChange={(value: string) => setData('location', value)}
                                        error={errors.location}
                                        region="PE"
                                        showCoordinates={true}
                                    />
                                </div>
                            </>
                        )}
                        {/* Selección de perro para celo/padrillo */}
                        {(data.type === 'Alerta de celo' || data.type === 'Alerta de padrillo disponible') && (
                            <ComboBoxField
                                id="dog_id"
                                label="Selecciona el perro"
                                value={data.dog_id || ''}
                                onChange={(v) => setData('dog_id', v)}
                                options={dogOptions}
                                error={errors.dog_id}
                            />
                        )}
                        {/* Selección de camada para camadas disponibles */}
                        {data.type === 'Alerta de camadas disponibles' && (
                            <ComboBoxField
                                id="litter_id"
                                label="Selecciona la camada"
                                value={data.litter_id || ''}
                                onChange={(v) => setData('litter_id', v)}
                                options={litterOptions}
                                error={errors.litter_id}
                            />
                        )}
                        {/* 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="notification-form"
                        disabled={processing || !isFormValid}
                    >
                        {processing && (
                            <LoaderCircle className="h-4 w-4 animate-spin" />
                        )}
                        Guardar
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
