import generateQueryString from '@/lib/generateQueryString';
import trackAnalyticsEvent from '@/lib/trackAnalyticsEvent';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { dark, darkLine } from '../../styles/colors';
import Modal, { ModalProps } from '../Modal';
import ForgotForm from './ForgotForm';
import LoginForm from './LoginForm';
import { RecaptchaTerms } from './RecaptchaTerms';
import RegisterSection from './RegisterSection';
import { UserNotVerifiedNotice } from './VerifyEmailModal';
import {
  AuthButton,
  AuthSeparator,
  AuthSeparatorLine,
  ButtonLink,
  CancelButton,
  FormLabel,
  FormLink,
  Header,
  MainAuthModalWrapper,
  MainAuthTab,
  MainAuthTabBar,
  MainAuthTabContent,
  ModalBodyTerms,
  Notice,
} from './styles';

const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;
export type AuthModalState =
  | 'login'
  | 'register'
  | 'resetpassword'
  | 'forgot'
  | 'usernotverified'
  | 'notregistered'
  | null;
export type AuthModalProps = Omit<Omit<ModalProps, 'children'>, 'open'> & {
  authModalState: AuthModalState;
  directToStudio?: boolean;
  setAuthModalState: (state: AuthModalState) => void;
};

const AuthModal = (props: AuthModalProps) => {
  const router = useRouter();
  const { authModalState: internalAuthModalState, setAuthModalState, directToStudio = true } = props;
  const authModalState = internalAuthModalState === 'register' ? 'login' : internalAuthModalState;
  const [email, setEmail] = useState('');
  const [notRegisteredNotice, setNotRegisteredNotice] = useState(false);

  useEffect(() => {
    if (authModalState === 'notregistered') {
      setAuthModalState('register');
      setNotRegisteredNotice(true);
    }
  }, [authModalState]);

  const modalProps = {
    ...props,
    open: !!authModalState,
  };
  return (
    <Modal
      style={{
        borderColor: darkLine,
        backgroundColor: 'white',
        color: dark,
        position: 'relative',
      }}
      bodyStyle={{
        padding: 0,
      }}
      hideCloseButton
      {...modalProps}
    >
      <MainAuthModalWrapper>
        {['register', 'login'].includes(authModalState || '') && (
          <MainAuthTabBar>
            <MainAuthTab
              active={['login'].includes(authModalState || '')}
              onClick={() => {
                setAuthModalState('login');
                trackAnalyticsEvent({
                  name: 'Landing Button Clicked',
                  properties: {
                    text: 'Log In',
                    location: 'Auth Modal (Tab)',
                  },
                });
              }}
            >
              Log In
            </MainAuthTab>
            {/* <MainAuthTab
              active={authModalState === 'register'}
              onClick={() => {
                setAuthModalState('register');
                trackAnalyticsEvent({
                  name: 'Landing Button Clicked',
                  properties: {
                    text: 'Sign Up',
                    location: 'Auth Modal (Tab)',
                  },
                });
              }}
            >
              Sign Up
            </MainAuthTab> */}
          </MainAuthTabBar>
        )}
        <MainAuthTabContent>
          {['login'].includes(authModalState || '') && (
            <>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  justifyContent: 'center',
                  width: '100%',
                  margin: '15px 0 25px',
                }}
              >
                <img src="/images/wordmark-black.svg" height={30} width={130} alt="WavTool Logo" />
              </div>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '10px',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: '20px',
                }}
              >
                <ButtonLink
                  target={directToStudio ? '' : '_blank'}
                  href={`${SERVER_URL}/auth/google${generateQueryString(router.query)}`}
                >
                  <AuthButton
                    onClick={() => {
                      props.onClose();
                      trackAnalyticsEvent({
                        name: 'Landing Button Clicked',
                        properties: {
                          text: 'Log in with Google',
                          location: 'Auth Modal',
                        },
                      });
                    }}
                  >
                    Log in with Google
                    <img src="/images/icons/Google.svg" height={24} width={24} alt="Google Logo" />
                  </AuthButton>
                </ButtonLink>
                <ButtonLink
                  target={directToStudio ? '' : '_blank'}
                  href={`${SERVER_URL}/auth/facebook${generateQueryString(router.query)}`}
                >
                  <AuthButton
                    onClick={() => {
                      props.onClose();
                      trackAnalyticsEvent({
                        name: 'Landing Button Clicked',
                        properties: {
                          text: 'Log in with Facebook',
                          location: 'Auth Modal',
                        },
                      });
                    }}
                  >
                    Log in with Facebook
                    <img src="/images/icons/Facebook.svg" height={24} width={24} alt="Facebook logo" />
                  </AuthButton>
                </ButtonLink>
              </div>

              <AuthSeparator>Or</AuthSeparator>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                <LoginForm
                  setAuthModalState={setAuthModalState}
                  setEmail={setEmail}
                  onCancel={() => {
                    props.onClose();
                    trackAnalyticsEvent({
                      name: 'Landing Button Clicked',
                      properties: {
                        text: 'Cancel',
                        location: 'Auth Modal',
                      },
                    });
                  }}
                />
                <FormLink onClick={() => setAuthModalState('forgot')}>Forgot Password</FormLink>
              </div>
            </>
          )}

          {props.authModalState === 'register' && (
            <>
              {notRegisteredNotice && (
                <Notice className="flash">
                  You are not registered.
                  <br />
                  Please register below.
                </Notice>
              )}

              <RegisterSection
                directToStudio={directToStudio}
                onCancel={() => {
                  props.onClose();
                  setNotRegisteredNotice(false);
                }}
                queryString={generateQueryString(router.query)}
              />

              <ModalBodyTerms style={{ marginBottom: 0 }}>
                <div className="labelWrapper">
                  <FormLabel style={{ fontSize: 12 }}>
                    By signing up, you confirm that you have read and agree to the{' '}
                    <a target="_blank" href="/static/terms.html" style={{ fontSize: 12 }}>
                      Terms of Service
                    </a>{' '}
                    and the{' '}
                    <a target="_blank" href="/static/privacy-policy.html" style={{ fontSize: 12 }}>
                      Privacy Policy
                    </a>
                  </FormLabel>
                </div>
              </ModalBodyTerms>
            </>
          )}

          {props.authModalState === 'forgot' && (
            <>
              <Header>Reset Password</Header>
              <ForgotForm setAuthModalState={setAuthModalState} />
              <AuthSeparatorLine />
              <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center' }}>
                <CancelButton onClick={() => setAuthModalState('login')}>Back to login</CancelButton>
              </div>
            </>
          )}

          {props.authModalState === 'usernotverified' && (
            <>
              <Header>Email not verified</Header>

              <UserNotVerifiedNotice email={email} />

              <AuthSeparatorLine />
              <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center' }}>
                <CancelButton onClick={() => setAuthModalState('login')}>Back to login</CancelButton>
              </div>
            </>
          )}

          <div style={{ borderTop: `1px solid ${darkLine}`, paddingTop: 10, marginTop: 10, marginBottom: 0 }}>
            <RecaptchaTerms />
          </div>
        </MainAuthTabContent>
      </MainAuthModalWrapper>
    </Modal>
  );
};

export default AuthModal;
