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

import _ from 'lodash';
import {
    Check,
    CheckCircleIcon,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import {
    AdminActionItemType,
    AdminActionMenuItemType,
} from '@/api/types';
import SkeletonList from '@/components/SkeletonList';
import {
    Empty,
    EmptyContent,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
    Lang,
    LL,
} from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';

import CollectionFields from '../components/CollectionFields/CollectionFields';
import { requiredValidation } from '../components/CollectionView/utils';
import { Button } from '../components/ui/button';
import {
    MobileDialog,
    MobileDialogButton,
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '../components/ui/mobile';
import { toast } from './ToastRoot';

type ActionOpenParams = {
    collection: string;
    action: AdminActionMenuItemType;
    ids: string[];
    onSuccess: () => void;
}

type ActionDialogRefProps = {
    open: (params: ActionOpenParams) => void;
}

export const actionDialogRef = React.createRef<ActionDialogRefProps>();

const ActionDialog = forwardRef<ActionDialogRefProps, {}>((props, ref) => {


    const { isMobile } = useAppConfigStore();

    const [action, setAction] = useState<AdminActionItemType | null>(null);

    const idsRef = useRef<string[]>([]);
    const collectionRef = useRef<string>("");

    const onSuccessRef = useRef<() => void>(null);
    const [open, setOpen] = useState<boolean>(false);


    const values = useRef<any>({});

    const [loading, setLoading] = useState<boolean>(false);

    const [done, setDone] = useState<boolean>(false);

    const [url, setUrl] = useState<string | null>(null);



    const loadActionArgs = (item: AdminActionItemType) => {

        if (!item?.key) return;
        rpc.prepareAction({
            collection: collectionRef.current,
            action: item?.key,
            _ids: idsRef.current,
        }).then((data) => {
            setAction(data?.result);
        });

    }

    useEffect(() => {
        if (!open) {
            setAction(null);
        }
    }, [open]);

    useImperativeHandle(ref, () => ({
        open: (params: ActionOpenParams) => {
            setDone(false);
            setUrl(null);
            setLoading(false);
            values.current = {};
            collectionRef.current = params.collection;

            idsRef.current = params.ids;
            loadActionArgs(params.action);

            onSuccessRef.current = params.onSuccess;
            setOpen(true);
        }
    }));



    const onUpdate = () => {

        if (!action) return;

        if (action?.args) {
            let valid = requiredValidation(values.current, action.args, values.current, []);
            if (valid.length > 0) {
                toast.error(`${valid[0]} ${Lang.key('is_required')}`);
                return;
            }
        }


        if (!action.key) {
            toast.error(Lang.key('action_error_required'));
            return;
        }

        let loading = toast.loading(Lang.key('executing'));

        console.log('➡️➡️➡️➡️➡️ 📍 ActionDialog: ', values.current,);


        rpc.runAction({
            collection: collectionRef.current,
            action: action.key,
            _ids: idsRef.current,
            values: values.current,
        }).then((data) => {

            onSuccessRef.current?.();

            setDone(true);

            setUrl(data?.result?.payload?.url ?? null);

            toast.success(Lang.key('action_dialog_success_title'));
        }).finally(() => {
            toast.dismiss(loading);
        });

    }

    if (isMobile) {

        if (!action?.args) {

            return <MobileDialog
                opened={open}
                onBackdropClick={() => setOpen(false)}
                title={action?.title}
                content={done ? Lang.key('action_dialog_success_title') : Lang.key('run_action_confirm')}
                buttons={
                    <>
                        <MobileDialogButton onClick={() => setOpen(false)}>
                            {Lang.key('close')}
                        </MobileDialogButton>
                        {url && <MobileDialogButton onClick={() => {
                            if (url) {
                                window.open(url, '_blank');
                            }
                        }}>
                            {Lang.key('open_link')}
                        </MobileDialogButton>}
                        {!done && <MobileDialogButton strong onClick={onUpdate}>
                            {Lang.key('execute')}
                        </MobileDialogButton>}
                    </>
                }
            />

        }


        return <MobilePopup opened={open} onBackdropClick={() => setOpen(false)}>
            <MobilePage>
                <MobileNavbar title={action?.title}

                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />


                {done ? <>

                    <Empty>
                        <EmptyHeader>
                            <EmptyMedia variant="icon">
                                <CheckCircleIcon />
                            </EmptyMedia>
                            <EmptyTitle>{Lang.key('action_dialog_success_title')}</EmptyTitle>
                            <EmptyDescription>{action?.title}</EmptyDescription>

                        </EmptyHeader>
                        {!!url && <EmptyContent>
                            <Button onClick={() => {
                                if (url) {
                                    window.open(url, '_blank');
                                }
                            }}>
                                {Lang.key('open_link')}
                            </Button>

                        </EmptyContent>}

                    </Empty>





                </> : <>


                    {!action && <SkeletonList count={3} />}


                    {action?.args && <CollectionFields
                        noPaddingBottom
                        structure={action?.args}
                        valuesRef={values}

                    />}



                </>}

                <MobileFab
                    onClick={onUpdate}
                    className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"
                    icon={<Check />}
                    text={Lang.key('execute')}
                    textPosition="after"
                />

            </MobilePage>
        </MobilePopup>
    }



    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={action?.title}
            width={560}
            height={"auto"}
            footer={
                <>
                    {!done && (
                        <Button onClick={onUpdate} disabled={loading || !action}>
                            {Lang.key('execute')}
                        </Button>
                    )}
                    <Button onClick={() => setOpen(false)} variant="outline">
                        {Lang.key('close')}
                    </Button>
                </>
            }
        >
            {done ? <>

                <Empty>
                    <EmptyHeader>
                        <EmptyMedia variant="icon">
                            <CheckCircleIcon />
                        </EmptyMedia>
                        <EmptyTitle>{Lang.key('action_dialog_success_title')}</EmptyTitle>
                        <EmptyDescription>{action?.title}</EmptyDescription>

                    </EmptyHeader>
                    {!!url && <EmptyContent>
                        <Button onClick={() => {
                            if (url) {
                                window.open(url, '_blank');
                            }
                        }}>
                            {Lang.key('open_link')}
                        </Button>

                    </EmptyContent>}

                </Empty>





            </> : <>

                {!action && <SkeletonList count={1} />}

                {action && <>{!!action?.args?.items ?
                    <CollectionFields
                        noPaddingBottom
                        structure={action?.args}
                        valuesRef={values}

                    /> :
                    <div className='p-4 text-center text-muted-foreground text-xs'>{Lang.key('press_execute_to_run')} <LL value={action?.title} /></div>}</>}



            </>}
        </SystemWindowDialog>






    );
});

export default ActionDialog;
