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

import {
    AlertDialog,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import {
    MobileDialog,
    MobileDialogButton,
} from '@/components/ui/mobile';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

export const confirmAlertRef = React.createRef<ConfirmAlertRef>();
type ConfirmAlertParams = {
    title: string;
    description: string;
    buttons: {
        label: string;
        onClick: () => void;
    }[]
}

type ConfirmAlertRef = {
    open: (props: ConfirmAlertParams) => void;
    close: () => void;
}


export const ConfirmAlert = forwardRef<ConfirmAlertRef, any>((props, ref) => {

    const { isMobile } = useAppConfigStore();
    const [open, setOpen] = useState(false);


    const [data, setData] = useState<ConfirmAlertParams | null>(null);

    useImperativeHandle(ref, () => ({
        open: (props: ConfirmAlertParams) => {
            setData(props);
            setOpen(true);
        },
        close: () => {
            setOpen(false);
        }
    }));

    if (isMobile) {
        return <MobileDialog
            opened={open}
            onBackdropClick={() => setOpen(false)}
            title={data?.title}
            content={data?.description}
            buttons={
                <div className='flex gap-2 flex-col w-full'>
                    {data?.buttons.map((button) => (
                        <MobileDialogButton
                            key={button.label} onClick={() => {
                                setOpen(false);
                                button.onClick();
                            }} strong>{button.label}</MobileDialogButton>
                    ))}
                </div>
            }
        />
    }


    return (
        <AlertDialog open={open} onOpenChange={setOpen}>

            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>{data?.title}</AlertDialogTitle>
                    <AlertDialogDescription>
                        {data?.description}
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                    {data?.buttons.map((button) => (
                        <Button key={button.label} onClick={() => {
                            confirmAlertRef.current?.close();
                            button.onClick();
                        }}>{button.label}</Button>
                    ))}
                </AlertDialogFooter>
            </AlertDialogContent>
        </AlertDialog>
    )
});

export default ConfirmAlert;