import React, {
  useEffect,
  useState,
} from 'react';

import { IoMdArrowBack } from 'react-icons/io';
import { RiLockPasswordLine } from 'react-icons/ri';

import { rpc } from '@/api/request';
import type {
  AuthEmailPrepareCFIType,
  ShmMsgAuthType,
} from '@/api/types';
import { toast } from '@/components/ToastRoot';
import { Button } from '@/components/ui/button';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
import {
  generateUUID,
  getAlphaNumericRandom,
} from '@/utils/helpers';

import { Input } from '../../components/ui/input';
import LoginAuth4App from './components/LoginAuth4App';
import LoginHeader from './components/LoginHeader';
import LoginMailAuthInput from './components/LoginMailAuthInput';
import LoginPageWrapper from './components/LoginPageWrapper';
import LoginPasswordInput from './components/LoginPasswordInput';
import LoginPhoneInput from './components/LoginPhoneInput';
import LoginTerms from './components/LoginTerms';
import PhoneLoginButton from './components/PhoneLoginButton';
import SocialLoginButtons from './components/SocialLoginButtons';

const OrLine = () => {

  return <div
    className='text-center text-sm text-gray-500 my-2'
  >{Lang.key('or')}</div>
}

const LoginPage = () => {

  const { isMobile } = useAppConfig();


  const reload = (message: string) => {
    // toast.success(message);
    window.location.reload();
  }


  const onSocAuth = (type: string) => {
    let key =
      new Date().getTime() +
      '-' +
      generateUUID(256) +
      '-' +
      getAlphaNumericRandom(100);

    let win = window.open(
      `https://auth4app.com/auth?soc=${type}&key=${key}`,
      '_blank'
    );

    const interval = setInterval(() => {
      if (win && win.closed) {
        clearInterval(interval);
        rpc.authSoc({ key }).then((data) => {
          if (data?.result) {
            localStorage.setItem('token', data.result);
            reload("Успешная авторизация");
          }
        });
      }
    }, 500);
  };


  const [login, setLogin] = React.useState('');
  const [password, setPassword] = React.useState('');

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

  const [step, setStep] = useState<"main" | "emailPassword" | "emailCodeConfirmation" | "phone">('main');

  const [prepareData, setPrepareData] = useState<AuthEmailPrepareCFIType | null>(null);


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

  const [confirmCode, setConfirmCode] = useState('');

  const onEmailPrepare = () => {

    if (!login) return;

    setLoading(true);

    rpc.authEmailPrepare({
      login: login
    }).then((e) => {

      if (!e.result?.find && !e.result?.isEmail) {

        toast.error(Lang.key('invalidLoginOrEmail'));

        return;
      }






      if (e?.result?.find) {
        setStep('emailPassword');
        return;
      } else {

        if (e?.result?.isEmail && e?.result?.canRegister) {





          setStep('emailCodeConfirmation');
        } else {
          toast.error(Lang.key('invalidLoginOrEmail'));

          return;
        }
      }


      setPrepareData(e.result ?? null);

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

  }

  const onPasswordAuth = () => {

    if (!login || !password) {
      return;
    }

    setLoading(true);
    rpc.authEmail({
      login: login,
      password: password
    }).then((e) => {

      if (e.result) {
        localStorage.setItem('token', e.result);
        reload(Lang.key('successfulAuthorization'));
      }
    }).finally(() => {
      setLoading(false);
    })

  }


  const codeConf = () => {


    if (!login || !password || !confirmCode) {
      return;
    }

    setLoading(true);
    rpc.authEmail({
      login: login,
      withEmailCode: true,
      code: +confirmCode,
      password: password
    }).then((token) => {
      if (token.result) {
        localStorage.setItem('token', token.result);
        reload(Lang.key('successfulAuthorization'));

      }


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

  }

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

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

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

      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);
              reload(Lang.key('successfulAuthorization'));
            }
            console.log(data);
          })
          .catch(() => {

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

      }, 5000);
    };



    return () => {

      clearInterval(msgAuthInterval);

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

  }, [msgAuthData, step])

  const onPhoneAuth = () => {

    if (!phone) return;

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

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


  }

  useEffect(() => {


    if (step == "emailCodeConfirmation" && login) {

      setPassword("");
      setConfirmCode("");
      rpc.authEmail({
        login: login,
        withEmailCode: true

      }).then(() => {
        toast.success(Lang.key('emailCodeConfirmationSent'));
      });
    }

    if (step == "main") {

      setPassword("");
      setConfirmCode("");
      setLogin("");
      setPhone("");
      setPrepareData(null);
      setMsgAuthData(null);

    }


  }, [step]);


  if (step == "phone") {


    return (
      <LoginPageWrapper>

        <LoginHeader
          title={Lang.key('phoneLogin')}
          onBack={() => {
            setStep('main');
            setPrepareData(null);
          }}
        />





        {!msgAuthData ? <>


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

        </> : <>
          <LoginAuth4App
            onCancelAuthWithPhoneNumber={() => {
              setStep('main');
              setPrepareData(null);
            }}
            msgAuthData={msgAuthData} />
        </>}




        {/*appStore.isNewYear && <Snowfall />*/}
      </LoginPageWrapper>
    );
  }


  if (step == "emailPassword") {



    return (
      <LoginPageWrapper>


        <LoginHeader title={Lang.key('enterPassword')} onBack={() => {
          setStep('main');
          setPrepareData(null);
        }} />



        <LoginPasswordInput
          onForgotPassword={() => {
            setStep('emailCodeConfirmation');
          }}
          password={password}
          setPassword={setPassword}
          onPasswordAuth={onPasswordAuth}
          loading={loading}
        />




      </LoginPageWrapper>
    );
  }


  if (step == "emailCodeConfirmation") {



    return (
      <LoginPageWrapper>
        <React.Fragment>

          <div className="text-3xl font-medium mb-2 flex items-center cursor-pointer active:opacity-50" onClick={() => {
            setStep('main');
            setPrepareData(null);
          }}>
            <IoMdArrowBack /> {prepareData?.find ? Lang.key('recoveryPassword') : Lang.key('registration')}
          </div>


          <div className="text-sm mb-4 mt-4 ">
            {Lang.key('emailCodeConfirmationSentToEmail')}
          </div>

          <Input
            className="my-2"
            icon={<RiLockPasswordLine />}
            id={'code'}

            placeholder={Lang.key('emailCodeConfirmation')}
            value={confirmCode}
            onChange={(e) => setConfirmCode(e.target.value.trim())}
            onKeyPress={(event: any) => {
              if (event.key === 'Enter') {
                codeConf();
              }
            }}
          />

          <Input
            type="password"
            className="my-2"
            icon={<RiLockPasswordLine />}
            id={'password'}
            placeholder={Lang.key('password')}
            value={password}
            security=""
            onChange={(e) => setPassword(e.target.value)}
            onKeyPress={(event: any) => {
              if (event.key === 'Enter') {
                codeConf();
              }
            }}
          />

          <Button
            disabled={!login || !confirmCode || !password}
            className='mt-2 w-full'
            onClick={() => {
              codeConf();
            }}

          >{Lang.key('continue')}</Button>





        </React.Fragment>
        {/*appStore.isNewYear && <Snowfall />*/}
      </LoginPageWrapper>
    );
  }




  return (
    <LoginPageWrapper>


      <LoginHeader title={Lang.key('login')} />




      <LoginMailAuthInput login={login} setLogin={setLogin} onEmailPrepare={onEmailPrepare} loading={loading} />


      <PhoneLoginButton
        onClick={() => {
          setStep("phone")
        }}
      />



      <SocialLoginButtons
        onSocAuth={onSocAuth}
      />




      <LoginTerms />


      {/*appStore.isNewYear && <Snowfall />*/}
    </LoginPageWrapper>
  );
}

export default LoginPage;
