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

import { rpc } from '@/api/request';
import { ShmMsgAuthType } from '@/api/types';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
    MobileBlock,
    MobileButton,
    MobileSheet,
} from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';

import LoginAuth4App from './LoginAuth4App';
import LoginPhoneInput from './LoginPhoneInput';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

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

export const phoneLoginModalRef = createRef<PhoneLoginModalRefProps>();

const PhoneLoginModal = forwardRef<PhoneLoginModalRefProps, {}>((_, ref) => {

    const [open, setOpen] = useState(false);

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

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

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

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

            msgAuthInterval = setInterval(() => {

                if (isRequesting) return;
                isRequesting = true;

                rpc.authPhone({
                    phone: phone,
                    code_id: msgAuthData.code_id,
                })
                    .then((data) => {
                        if (data.result?.token) {
                            if (msgAuthInterval) clearInterval(msgAuthInterval);
                            localStorage.setItem('token', data.result.token);
                            window.location.reload();
                        }
                        console.log(data);
                    })
                    .catch(() => {

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

            }, 5000);
        };



        return () => {

            clearInterval(msgAuthInterval);

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

    }, [msgAuthData, open])


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

    const [phone, setPhone] = useState('');
    const [loading, setLoading] = useState(false);
    const onPhoneAuth = () => {

        if (!phone) return;

        setLoading(true);
        rpc.authPhone({
            phone: phone
        }).then((e) => {

            if (e.result) {
                setMsgAuthData(e.result);
            }
        }).finally(() => {
            setLoading(false);
        })


    }


    const { isMobile } = useAppConfigStore();

    if (isMobile) {
        return <MobileSheet

            opened={open}
        //   onBackdropClick={() => setOpen(false)}
        >

            {!msgAuthData ? <>


                <LoginPhoneInput
                    phone={phone}
                    setPhone={setPhone}
                    onPhoneAuth={onPhoneAuth}
                    loading={loading}
                />

            </> : <>
                <LoginAuth4App
                    onCancelAuthWithPhoneNumber={() => {
                        setOpen(false);
                    }}
                    msgAuthData={msgAuthData} />
            </>}

            <MobileBlock>
                <MobileButton
                    onClick={() => {
                        setOpen(false);
                    }}
                >
                    {Lang.key('cancelAuthWithPhoneNumber')}
                </MobileButton>
            </MobileBlock>



        </MobileSheet>
    }
    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={Lang.key('phoneLogin')}
            width={400}
        >
            {!msgAuthData ? (
                <LoginPhoneInput
                    phone={phone}
                    setPhone={setPhone}
                    onPhoneAuth={onPhoneAuth}
                    loading={loading}
                />
            ) : (
                <LoginAuth4App
                    onCancelAuthWithPhoneNumber={() => setOpen(false)}
                    msgAuthData={msgAuthData}
                />
            )}
        </SystemWindowDialog>
    );
});

export default PhoneLoginModal;