import { Form } from '@inertiajs/react';
import { useState } from 'react';
import type { ReactNode } from 'react';
import {
    AlertDialog,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';

type Props = {
    /** The request to send once confirmed: `Controller.destroy.form(id)`. */
    action: { action: string; method: 'get' | 'post' };
    title: string;
    description: ReactNode;
    /** Label of the confirming button. */
    confirmLabel?: string;
    /** The button that opens the dialog. */
    children: ReactNode;
};

/**
 * Asks before something irreversible (deleting a record) is done. The
 * confirming button submits `action` as an Inertia form; the dialog closes
 * when the server has answered.
 */
export function ConfirmDialog({
    action,
    title,
    description,
    confirmLabel = 'Sil',
    children,
}: Props) {
    const [open, setOpen] = useState(false);

    return (
        <AlertDialog open={open} onOpenChange={setOpen}>
            <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>{title}</AlertDialogTitle>
                    <AlertDialogDescription>
                        {description}
                    </AlertDialogDescription>
                </AlertDialogHeader>
                {/*
                 * The dialog is portalled out of the page, but React still
                 * bubbles its events to the component that rendered it: a
                 * surrounding edit form must not be submitted along.
                 */}
                <div onSubmit={(event) => event.stopPropagation()}>
                    <Form
                        {...action}
                        options={{ preserveScroll: true }}
                        onFinish={() => setOpen(false)}
                    >
                        {({ processing }) => (
                            <AlertDialogFooter>
                                <AlertDialogCancel type="button">
                                    Vazgeç
                                </AlertDialogCancel>
                                <Button
                                    type="submit"
                                    variant="destructive"
                                    disabled={processing}
                                >
                                    {processing && <Spinner />}
                                    {confirmLabel}
                                </Button>
                            </AlertDialogFooter>
                        )}
                    </Form>
                </div>
            </AlertDialogContent>
        </AlertDialog>
    );
}
