import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

import {
  ERROR_CANT_USE_PASSWORDLESS_AUTH,
  ERROR_OTP_ALREADY_USED,
  ERROR_OTP_HAS_EXPIRED,
  ERROR_TOO_MANY_ATTEMPTS,
  ERROR_TWO_FA_IS_REQUIRED,
  ERROR_UI_LINK_WAS_EXPIRED,
  ERROR_USER_NOT_VALID,
} from '@/modules/@common/constants/errors';
import { LOGIN_PAGE } from '@/modules/@common/router/constants';

import Layout from '@/modules/auth/common/components/Layout/Layout';

const errorMap = {
  [ERROR_OTP_ALREADY_USED]: {
    title: 'You have already signed in with this password in another session',
    description: 'To sign in again, please request another password',
  },
  [ERROR_USER_NOT_VALID]: {
    title: 'Could not verify user',
    description: 'Please provide a valid email or try other sign in options',
  },
  [ERROR_OTP_HAS_EXPIRED]: {
    title: 'This password has expired',
    description: 'Please request a new one',
  },
  [ERROR_TWO_FA_IS_REQUIRED]: {
    title: '2-factor authentication is required',
    description: 'Please use other sign in options',
  },
  [ERROR_CANT_USE_PASSWORDLESS_AUTH]: {
    title: 'One-time password authentication is disabled for you',
    description: 'Please use other sign in options instead',
  },
  [ERROR_TOO_MANY_ATTEMPTS]: {
    title: 'Too many invalid attempts',
    description: 'You will be able to request a new password later, or use other sign in options',
  },
  [ERROR_UI_LINK_WAS_EXPIRED]: {
    title: 'The link expired',
    description: 'Please try again',
  },
};

function UserAuthError() {
  const router = useRouter();

  const data = errorMap[router.query.error] ?? {};

  useEffect(() => {
    if (!errorMap[router.query.error]) {
      router.replace(LOGIN_PAGE.path);
    }
  }, [router.query.errorKey]);

  return <Layout title={data.title} subTitle={data.description} />;
}

export default UserAuthError;
