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 { Button } from '@/components/ui/button';
import { MobileBlock } from '@/components/ui/mobile';
import { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { loginViaSocial } from '@/utils/socialAuth';

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';

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


  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;
