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

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('Terjadi kesalahan saat menyimpan data. 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>
    );
}
