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

import { XIcon } from 'lucide-react';

import { rpc } from '@/api/request';
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 ChangeEmailCodeInput from './components/ChangeEmailCodeInput';
import ChangeEmailInput from './components/ChangeEmailInput';

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

export const changeEmailDialogRef = createRef<ChangeEmailDialogRefProps>();

const ChangeEmailDialog = forwardRef<ChangeEmailDialogRefProps>((_, ref) => {
    const { isMobile } = useAppConfigStore();
    const { loadProfile } = useMainPage();
    const [open, setOpen] = useState(false);
    const [step, setStep] = useState<'email' | 'code'>('email');
    const [email, setEmail] = useState('');
    const [code, setCode] = useState('');
    const [loading, setLoading] = useState(false);
    const [resendLoading, setResendLoading] = useState(false);

    const resetState = () => {
        setStep('email');
        setEmail('');
        setCode('');
        setLoading(false);
        setResendLoading(false);
    };

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

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

    const onEmailSubmit = () => {
        if (!email) return;

        setLoading(true);
        rpc.authEmailSet({ email })
            .then(() => {
                toast.success(Lang.key('emailCodeConfirmationSent'));
                setStep('code');
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const onResend = () => {
        if (!email) return;

        setResendLoading(true);
        rpc.authEmailSet({ email })
            .then(() => {
                toast.success(Lang.key('emailCodeConfirmationSent'));
            })
            .finally(() => {
                setResendLoading(false);
            });
    };

    const onConfirm = () => {
        if (!email || !code) return;

        setLoading(true);
        rpc.authEmailSet({
            email,
            code: +code,
        })
            .then((data) => {
                if (data.result) {
                    toast.success(Lang.key('email_changed_successfully'));
                    loadProfile();
                    setOpen(false);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const content = step === 'email' ? (
        <ChangeEmailInput
            email={email}
            setEmail={setEmail}
            onEmailSubmit={onEmailSubmit}
            loading={loading}
        />
    ) : (
        <ChangeEmailCodeInput
            email={email}
            code={code}
            setCode={setCode}
            onConfirm={onConfirm}
            onResend={onResend}
            loading={loading}
            resendLoading={resendLoading}
        />
    );

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

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

export default ChangeEmailDialog;
