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 } from '@/api/types';
import { toast } from '@/componentsRoot/ToastRoot';
import { Button } from '@/components/ui/button';
import { MobileBlock } from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';
import {
  generateUUID,
  getAlphaNumericRandom,
} from '@/utils/helpers';

import { Input } from '../../components/ui/input';
import LoginHeader from './components/LoginHeader';
import LoginMailAuthInput from './components/LoginMailAuthInput';
import LoginPageWrapper from './components/LoginPageWrapper';
import LoginPasswordInput from './components/LoginPasswordInput';
import LoginTerms from './components/LoginTerms';
import PhoneLoginButton from './components/PhoneLoginButton';
import PhoneLoginModal, {
  phoneLoginModalRef,
} from './components/PhoneLoginModal';
import SocialLoginButtons from './components/SocialLoginButtons';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

const OrLine = () => {

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

const LoginPage = () => {

  const { isMobile } = useAppConfigStore();


  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?.token) {
            localStorage.setItem('token', data.result.token);
            reload("Успешная авторизация");
          }
        });
      }
    }, 500);
  };


  const [login, setLogin] = React.useState('');
  const [password, setPassword] = 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);
    })

  }



  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("");
      setPrepareData(null);

    }


  }, [step]);



  if (step == "emailPassword") {



    return (
      <LoginPageWrapper>


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



        <LoginPasswordInput
          login={login}
          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>

          {login && <input type="text" name="username" autoComplete="username" value={login} readOnly tabIndex={-1} className="absolute opacity-0 pointer-events-none h-0 w-0" aria-hidden />}
          <Input
            className="my-2"
            icon={<RiLockPasswordLine />}
            id="code"
            name="one-time-code"
            autoComplete="one-time-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-code"
            name="password"
            autoComplete="current-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('authorization')} />


      <MobileBlock outline>



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


        <PhoneLoginButton
          onClick={() => {
            phoneLoginModalRef.current?.open();
          }}
        />



        <SocialLoginButtons
          onSocAuth={onSocAuth}
        />

      </MobileBlock>



      <LoginTerms />


      <PhoneLoginModal ref={phoneLoginModalRef} />


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

export default LoginPage;
