import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { VisibilityOffRounded, VisibilityRounded } from '@mui/icons-material';

import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { FORGOT_PASSWORD_PAGE, PASSWORD_LESS_LOGIN_PAGE, SSO_LOGIN_PAGE } from '@/modules/@common/router/constants';

import {
  codeSelector,
  emailSelector,
  isCodeStepSelector,
  isSsoAuthProcessSelector,
  isSsoFailedSelector,
  passwordSelector,
} from './redux/selectors';
import {
  getUserDataEventAction,
  setCodeAction,
  setCodeStepAction,
  setEmailAction,
  setIsSsoAuthProcessAction,
  setPasswordAction,
  verifyCodeEventAction,
} from './redux/slices';
import { isFormLoadingSelector } from '@/modules/auth/common/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import Layout from '@/modules/auth/common/components/Layout/Layout';
import useSetRedirectUrl from '@/modules/auth/common/useSetRedirectUrl';
import useSsoBackgroundLogin from '@/modules/auth/common/useSsoBackgroundLogin';
import GoogleIconColored from '@/mui/customIcons/UnstyledIcons/GoogleIconColored';
import MicrosoftIconColored from '@/mui/customIcons/UnstyledIcons/MicrosoftIconColored';
import OktaIconColored from '@/mui/customIcons/UnstyledIcons/OktaIconColored';
import { Button, Divider, IconButton, InputAdornment, Link, Stack, TextField, Typography } from '@/mui/components';
import { CustomKeywords, CustomPeople } from '@/mui/components/CustomIcon';

function AuthPage() {
  const router = useRouter();
  const dispatch = useDispatch();
  const isFormLoading = useSelector(isFormLoadingSelector);
  const email = useSelector(emailSelector);
  const password = useSelector(passwordSelector);
  const isCodeStep = useSelector(isCodeStepSelector);
  const code = useSelector(codeSelector);
  const isSsoAuthProcess = useSelector(isSsoAuthProcessSelector);
  const isSsoFailed = useSelector(isSsoFailedSelector);
  const { initSsoBackgroundLoginFlow, getRedirectUrl } = useSsoBackgroundLogin();
  const [showPassword, togglePassword] = useState(false);

  const { code: ssoCode, error } = router.query;

  const onSubmit = (event) => {
    event.preventDefault();

    dispatch(!isCodeStep ? getUserDataEventAction() : verifyCodeEventAction());
  };

  const { isRedirectUrlAdded } = useSetRedirectUrl();

  useEffect(() => {
    if (error) {
      dispatch(
        showNotificationAction({
          type: TYPE_ERROR,
          message: 'Login failed or account is not configured for SSO',
        }),
      );
    }

    if (ssoCode) {
      dispatch(setIsSsoAuthProcessAction(true));
      dispatch(
        getUserDataEventAction({
          ssoCode,
          redirectUrl: getRedirectUrl(),
        }),
      );
    } else {
      initSsoBackgroundLoginFlow();
    }
  }, []);

  return (
    <Layout
      shouldHideContent={!isRedirectUrlAdded || ssoCode || isSsoAuthProcess}
      title={!isCodeStep ? 'Sign In' : 'Two-Factor Authentication'}
      subTitle={isCodeStep && 'Enter the verification code sent to your E-mail'}
      firstSection={
        <Stack component="form" disabled={isFormLoading} onSubmit={onSubmit} spacing={3} fullWidth>
          {!isCodeStep ? (
            <>
              <Stack spacing={2}>
                <TextField
                  data-id="email"
                  type="email"
                  variant="outlined"
                  placeholder="Email"
                  autoComplete="username"
                  value={email}
                  onChange={(event) => dispatch(setEmailAction(event.target.value))}
                  disabled={isFormLoading}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <CustomPeople />
                      </InputAdornment>
                    ),
                  }}
                />
                <TextField
                  data-id="password"
                  type={showPassword ? 'text' : 'password'}
                  variant="outlined"
                  placeholder="Password"
                  autoComplete="current-password"
                  value={password}
                  onChange={(event) => dispatch(setPasswordAction(event.target.value))}
                  disabled={isFormLoading}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <CustomKeywords />
                      </InputAdornment>
                    ),
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton onClick={() => togglePassword((e) => !e)}>
                          {showPassword ? <VisibilityOffRounded /> : <VisibilityRounded />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />
              </Stack>
              <Stack direction="row" justifyContent="space-between" alignItems="center">
                <Button
                  type="submit"
                  data-id="signin-submit"
                  variant="contained"
                  color="primary"
                  size="large"
                  shape="circular"
                  disabled={isFormLoading}
                >
                  Sign in
                </Button>{' '}
                <Link
                  variant="body2"
                  fontWeight={400}
                  data-id="forgot-password"
                  href="/"
                  color={!isFormLoading ? 'text.primary' : 'text.disabled'}
                  disabled={isFormLoading}
                  onClick={(event) => {
                    event.preventDefault();

                    if (!isFormLoading) {
                      router.push(FORGOT_PASSWORD_PAGE.path);
                    }
                  }}
                >
                  Forgot password?
                </Link>
              </Stack>
            </>
          ) : (
            <>
              <TextField
                data-id="code"
                type="password"
                variant="outlined"
                placeholder="Code"
                value={code}
                onChange={(event) => dispatch(setCodeAction(event.target.value))}
                disabled={isFormLoading}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <CustomKeywords />
                    </InputAdornment>
                  ),
                }}
              />
              <Stack justifyContent="space-between" alignItems="center" direction="row">
                <Button
                  data-id="signin-submit"
                  variant="contained"
                  color="primary"
                  type="submit"
                  disabled={isFormLoading}
                  size="large"
                  shape="circular"
                >
                  Sign in
                </Button>
                <Link
                  variant="body2"
                  fontWeight={400}
                  data-id="return-to-log-in"
                  href="/"
                  color={!isFormLoading ? 'text.primary' : 'text.disabled'}
                  disabled={isFormLoading}
                  onClick={(event) => {
                    event.preventDefault();

                    if (!isFormLoading) {
                      dispatch(setCodeStepAction(false));
                      dispatch(setCodeAction(''));
                    }
                  }}
                >
                  Back
                </Link>
              </Stack>
            </>
          )}
        </Stack>
      }
      secondSection={
        !isCodeStep && (
          <Stack spacing={2} fullWidth>
            <Button
              data-id="signin-sso"
              variant="outlined"
              color="info"
              disabled={isFormLoading || isSsoFailed}
              onClick={() => router.push(SSO_LOGIN_PAGE.path)}
              fullWidth
              shape="circular"
              endIcon={
                <Stack direction="row" alignItems="center" spacing={1} divider={<Divider flexItem />}>
                  <GoogleIconColored />
                  <MicrosoftIconColored />
                  <OktaIconColored />
                </Stack>
              }
            >
              Continue with
            </Button>
            <Button
              data-id="passwordless-auth"
              variant="outlined"
              color="info"
              disabled={isFormLoading}
              fullWidth
              shape="circular"
              onClick={() => router.push(PASSWORD_LESS_LOGIN_PAGE.path)}
            >
              Sign in with one-time password
            </Button>
          </Stack>
        )
      }
      footer={
        !isCodeStep && (
          <>
            <Typography variant="inherit">New to AnyClip?</Typography>
            &nbsp;
            <Link target="_blank" href="https://anyclip.com/">
              Get started now
            </Link>
          </>
        )
      }
    />
  );
}

export default AuthPage;
