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

import { XIcon } from 'lucide-react';

import { rpc } from '@/api/request';
import { ShmMsgSetType } from '@/api/types';
import {
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';

import { toast } from '../ToastRoot';
import ChangePhoneAuth4App from './components/ChangePhoneAuth4App';
import ChangePhoneInput from './components/ChangePhoneInput';

type ChangePhoneDialogRefProps = {
    open: () => void;
    close: () => void;
}


export const changePhoneDialogRef = createRef<ChangePhoneDialogRefProps>();

const ChangePhoneDialog = forwardRef<ChangePhoneDialogRefProps>((prps, ref) => {


    const { isMobile } = useAppConfigStore();

    const { loadProfile } = useMainPage();
    const [open, setOpen] = useState(false);


    const [msgAuthData, setMsgAuthData] = useState<ShmMsgSetType | null>(null);


    useImperativeHandle(ref, () => ({
        open: () => {

            setMsgAuthData(null);
            setPhone('');
            setOpen(true);
        },
        close: () => {
            setOpen(false);

        }
    }));

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

    const [phone, setPhone] = useState('');

    const [loading, setLoading] = useState(false);
    const onPhoneAuth = () => {
        if (!phone) return;
        setLoading(true);
        rpc.authPhoneSet({
            phone: phone,
        }).then((e) => {
            setMsgAuthData(e.result);
        }).finally(() => {
            setLoading(false);
        });
    }

    useEffect(() => {
        let msgAuthInterval: any = null;

        let isRequesting = false;
        if (msgAuthData && phone && open) {

            msgAuthInterval = setInterval(() => {

                if (isRequesting) return;
                isRequesting = true;

                rpc.authPhoneSet({
                    phone: phone,
                    code_id: msgAuthData.code_id,
                })
                    .then((data) => {
                        if (data.result?.auth) {

                            toast.success(Lang.key('phone_changed_successfully'));
                            loadProfile();
                            setOpen(false);


                        }

                    })
                    .catch(() => {

                    }).finally(() => {
                        isRequesting = false;
                    });

            }, 5000);
        };



        return () => {

            clearInterval(msgAuthInterval);

            if (msgAuthData) {
                setMsgAuthData(null);
            }
        }

    }, [msgAuthData, open])


    if (isMobile) {

        return <MobilePopup
            opened={open}
            onBackdropClick={() => setOpen(false)}
        >
            <MobilePage>
                <MobileNavbar
                    title={Lang.key('change_phone')}
                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />

                {!msgAuthData ? <ChangePhoneInput
                    phone={phone}
                    setPhone={setPhone}
                    onPhoneAuth={onPhoneAuth}
                    loading={loading}
                /> : <ChangePhoneAuth4App
                    msgAuthData={msgAuthData}
                    onCancelAuthWithPhoneNumber={() => {
                        setOpen(false);
                    }}
                />}

            </MobilePage>
        </MobilePopup>
    }

    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={(val) => {
                if (!val) {
                    setOpen(false);
                }
            }}
            title={Lang.key('change_phone')}
            width={448}
            height={'auto'}

        >

            {!msgAuthData ? <ChangePhoneInput
                phone={phone}
                setPhone={setPhone}
                onPhoneAuth={onPhoneAuth}
                loading={loading}
            /> : <ChangePhoneAuth4App
                msgAuthData={msgAuthData}
                onCancelAuthWithPhoneNumber={() => {
                    setOpen(false);
                }}
            />}

        </SystemWindowDialog>
    )
});


export default ChangePhoneDialog;