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

import { Button } from '@/components/ui/button';
import {
    MobileDialog,
    MobileDialogButton,
} from '@/components/ui/mobile';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import useAppConfigStore from '@/stores/appConfig';

/** Above regular modals (stackIndex 0–2) so confirms always appear on top */
const CONFIRM_ALERT_STACK_INDEX = 100;

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>
            }
        />
    }

    const buttons = data?.buttons ?? [];

    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            width={400}
            height="auto"
            className="max-h-[calc(100vh-2rem)]"
            bodyClassName="flex-none overflow-y-auto min-h-0"
            //  stackIndex={CONFIRM_ALERT_STACK_INDEX}
            closeOnOverlayClick={false}
            showCloseButton={false}
            footer={
                <div className="flex w-full flex-row flex-wrap justify-end gap-2">
                    {buttons.map((button, index) => {
                        const isPrimary =
                            buttons.length === 1 || index === buttons.length - 1;
                        return (
                            <Button
                                key={`${button.label}-${index}`}
                                variant={isPrimary ? 'default' : 'outline'}
                                className="min-w-[5.5rem]"
                                onClick={() => {
                                    confirmAlertRef.current?.close();
                                    button.onClick();
                                }}
                            >
                                {button.label}
                            </Button>
                        );
                    })}
                </div>
            }
        >
            <div className="flex flex-col gap-2">
                {data?.title && (
                    <h2 className="text-lg font-semibold leading-snug text-foreground">
                        {data.title}
                    </h2>
                )}
                {data?.description && (
                    <p className="text-sm leading-relaxed text-muted-foreground whitespace-pre-wrap">
                        {data.description}
                    </p>
                )}
            </div>
        </SystemWindowDialog>
    );
});

export default ConfirmAlert;
