import { Head, useForm } from '@inertiajs/react';
import { Bell, Landmark, ShieldCheck, UserPlus, Wallet } from 'lucide-react';
import type { FormEvent } from 'react';
import { useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';

type NotificationSettings = {
    notify_new_user_registered: boolean;
    notify_investment_pending: boolean;
    notify_withdrawal_requested: boolean;
    notify_kyc_submitted: boolean;
};

type Props = {
    settings: NotificationSettings;
};

function ToggleRow({
    id,
    checked,
    onCheckedChange,
    title,
    description,
    icon: Icon,
}: {
    id: keyof NotificationSettings;
    checked: boolean;
    onCheckedChange: (value: boolean) => void;
    title: string;
    description: string;
    icon: typeof Bell;
}) {
    return (
        <div className="flex items-start gap-3 rounded-lg border border-border/80 bg-background/50 p-4">
            <Checkbox
                checked={checked}
                className="mt-0.5"
                id={id}
                onCheckedChange={(value) => onCheckedChange(value === true)}
            />
            <div className="grid min-w-0 flex-1 gap-1">
                <Label className="flex cursor-pointer items-center gap-2 font-medium leading-snug" htmlFor={id}>
                    <Icon className="text-muted-foreground size-4 shrink-0" aria-hidden />
                    {title}
                </Label>
                <p className="text-muted-foreground text-sm leading-relaxed">{description}</p>
            </div>
        </div>
    );
}

export default function NotificationSettings({ settings }: Props) {
    const form = useForm<NotificationSettings>({
        notify_new_user_registered: settings.notify_new_user_registered,
        notify_investment_pending: settings.notify_investment_pending,
        notify_withdrawal_requested: settings.notify_withdrawal_requested,
        notify_kyc_submitted: settings.notify_kyc_submitted,
    });
    const [saveConfirmOpen, setSaveConfirmOpen] = useState(false);

    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setSaveConfirmOpen(true);
    }

    function executeSave() {
        form.put('/admin/notificaciones', {
            preserveScroll: true,
            onFinish: () => setSaveConfirmOpen(false),
        });
    }

    return (
        <>
            <Head title="Notificaciones" />

            <div className="mx-auto max-w-3xl space-y-8">
                <Heading
                    title="Notificaciones"
                    description="Elige qué avisos por correo reciben todos los administradores cuando hay actividad pendiente de revisión."
                />

                <form className="space-y-6" onSubmit={submit}>
                    <Card className="border-border/80 shadow-sm">
                        <CardHeader className="border-b border-border/60 bg-muted/20 pb-4">
                            <div className="flex gap-3">
                                <div className="bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-lg">
                                    <Bell className="size-5" aria-hidden />
                                </div>
                                <div className="min-w-0 space-y-1">
                                    <CardTitle className="text-base">Notificaciones</CardTitle>
                                    <CardDescription className="text-sm leading-relaxed">
                                        Los correos se envían a todas las cuentas con rol de administrador. 
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-3 pt-6">
                            <ToggleRow
                                checked={form.data.notify_new_user_registered}
                                description="Cuando un inversionista crea una cuenta nueva."
                                icon={UserPlus}
                                id="notify_new_user_registered"
                                title="Nuevo usuario registrado"
                                onCheckedChange={(value) =>
                                    form.setData('notify_new_user_registered', value)
                                }
                            />
                            <InputError message={form.errors.notify_new_user_registered} />

                            <ToggleRow
                                checked={form.data.notify_investment_pending}
                                description="Nueva inversión por depósito externo pendiente de aprobación."
                                icon={Landmark}
                                id="notify_investment_pending"
                                title="Inversión por aprobar"
                                onCheckedChange={(value) =>
                                    form.setData('notify_investment_pending', value)
                                }
                            />
                            <InputError message={form.errors.notify_investment_pending} />

                            <ToggleRow
                                checked={form.data.notify_withdrawal_requested}
                                description="Nuevo retiro solicitado por un inversionista."
                                icon={Wallet}
                                id="notify_withdrawal_requested"
                                title="Nuevo retiro solicitado"
                                onCheckedChange={(value) =>
                                    form.setData('notify_withdrawal_requested', value)
                                }
                            />
                            <InputError message={form.errors.notify_withdrawal_requested} />

                            <ToggleRow
                                checked={form.data.notify_kyc_submitted}
                                description="Cuando un inversionista envía su expediente de verificación de identidad."
                                icon={ShieldCheck}
                                id="notify_kyc_submitted"
                                title="Nueva solicitud de verificación KYC"
                                onCheckedChange={(value) => form.setData('notify_kyc_submitted', value)}
                            />
                            <InputError message={form.errors.notify_kyc_submitted} />
                        </CardContent>
                    </Card>

                    <div className="border-border bg-background/95 supports-[backdrop-filter]:bg-background/80 sticky bottom-0 z-10 flex flex-wrap items-center justify-between gap-3 rounded-lg border px-4 py-3 shadow-sm backdrop-blur">
                        <p className="text-muted-foreground text-sm">
                            {form.isDirty
                                ? 'Hay cambios sin guardar.'
                                : 'Todos los cambios están guardados.'}
                        </p>
                        <Button disabled={form.processing || !form.isDirty} type="submit">
                            {form.processing ? 'Guardando…' : 'Guardar preferencias'}
                        </Button>
                    </div>
                </form>
            </div>

            <ConfirmActionModal
                cancelLabel="Seguir editando"
                confirmLabel="Sí, guardar"
                description="Estas preferencias aplican a todos los administradores de la plataforma."
                open={saveConfirmOpen}
                processing={form.processing}
                title="¿Guardar la configuración de notificaciones?"
                onConfirm={executeSave}
                onOpenChange={setSaveConfirmOpen}
            />
        </>
    );
}

NotificationSettings.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Notificaciones', href: '/admin/notificaciones' },
    ],
};
