import { Form } from '@inertiajs/react';
import type { ReactNode } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';

type FormDialogProps = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    title: string;
    action: React.ComponentProps<typeof Form>['action'];
    resetOnSuccess?: boolean;
    onSuccess?: () => void;
    submitDisabled?: boolean;
    submitLabel?: ReactNode;
    submittingLabel?: ReactNode;
    children:
    | ReactNode
    | ((ctx: {
        errors: Record<string, string>;
        processing: boolean;
    }) => ReactNode);
};

export function FormDialog({
    open,
    onOpenChange,
    title,
    action,
    resetOnSuccess,
    onSuccess,
    submitDisabled = false,
    submitLabel = 'Simpan',
    submittingLabel = 'Menyimpan...',
    children,
}: FormDialogProps) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <Form
                    action={action}
                    resetOnSuccess={resetOnSuccess}
                    onSuccess={onSuccess}
                    onError={() => {
                        toast.error('Ada data yang belum sesuai, silakan periksa kembali input Anda.');
                    }}
                >
                    {({ errors, processing }) => (
                        <>
                            <DialogHeader>
                                <DialogTitle>{title}</DialogTitle>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                {typeof children === 'function'
                                    ? children({ errors, processing })
                                    : children}
                            </div>
                            <DialogFooter>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => onOpenChange(false)}
                                >
                                    Batal
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={processing || submitDisabled}
                                >
                                    {processing ? submittingLabel : submitLabel}
                                </Button>
                            </DialogFooter>
                        </>
                    )}
                </Form>
            </DialogContent>
        </Dialog>
    );
}
