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

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

import { rpc } from '@/api/request';
import { StructureType } from '@/api/types';
import {
    Empty,
    EmptyContent,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import CollectionFields from './CollectionFields/CollectionFields';
import { requiredValidation } from './CollectionView/utils';
import { toast } from './ToastRoot';
import { Button } from './ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from './ui/dialog';
import {
    MobileDialog,
    MobileDialogButton,
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from './ui/mobile';

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

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

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

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


    const { isMobile } = useAppConfig();

    const [action, setAction] = useState<StructureType | 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);

    useImperativeHandle(ref, () => ({
        open: (params: ActionOpenParams) => {
            setDone(false);
            setUrl(null);
            setLoading(false);
            values.current = {};
            collectionRef.current = params.collection;
            setAction(params.action);
            idsRef.current = params.ids;
            onSuccessRef.current = params.onSuccess;
            setOpen(true);
        }
    }));



    const onUpdate = () => {

        if (!action) return;

        let _values = {
            ...values.current,
            ids: idsRef.current,
        }

        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);


        rpc.runAction({
            collection: collectionRef.current,
            action: action.key,
            args: _values
        }).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?.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 (
        <Dialog
            open={open}
            onOpenChange={(open) => setOpen(open)}

        >

            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {action?.title}
                    </DialogTitle>
                </DialogHeader>


                {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?.args && <CollectionFields
                        noPaddingBottom
                        structure={action?.args}
                        valuesRef={values}

                    />}



                </>}

                <DialogFooter>
                    {!done && <Button onClick={onUpdate} disabled={loading}>{Lang.key('execute')}</Button>}
                    <Button onClick={() => setOpen(false)} variant="outline">{Lang.key('close')}</Button>
                </DialogFooter>

            </DialogContent>
        </Dialog>






    );
});

export default ActionDialog;
