import {
    createRef,
    forwardRef,
    useImperativeHandle,
    useState,
} from 'react';

import {
    Dialog,
    DialogButton,
} from 'konsta/react';

type AlertOpenProps = {
    title: string;
    content: string | React.ReactNode;
    buttons: {
        text: string;
        onClick?: () => void;
    }[];
}

type AlertRootRefType = {
    show: (params: AlertOpenProps) => void;
}


export const alertRootRef = createRef<AlertRootRefType>();


export const showAlert = (params: AlertOpenProps) => {
    alertRootRef.current?.show(params);
}

const AlertRoot = forwardRef<AlertRootRefType, {}>((_, ref) => {


    const [params, setParams] = useState<AlertOpenProps | null>(null);

    useImperativeHandle(ref, () => ({
        show: (params) => {
            setParams(params);

        },

    }));




    return <Dialog
        opened={!!params}
        onBackdropClick={() => setParams(null)}
        title={params?.title}
        content={params?.content}
        buttons={
            <div>
                {params?.buttons.map((button) => (
                    <DialogButton key={button.text} onClick={() => {
                        button.onClick?.();
                        setParams(null);
                    }}>
                        {button.text}
                    </DialogButton>
                ))}
            </div>
        }
    />

});

export default AlertRoot;