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 { passwordRegExp } from '@/modules/@common/constants/validation';
import { CREATE_PASSWORD_PAGE } from '@/modules/@common/router/constants';

import { emailSelector, password2Selector, passwordSelector } from './redux/selectors';
import { setFieldAction, submitPasswordAction, verifyCodeAction } from './redux/slices';
import { isFormLoadingSelector } from '@/modules/auth/common/redux/selectors';

import Layout from '@/modules/auth/common/components/Layout/Layout';
import { Button, IconButton, InputAdornment, Stack, TextField } from '@/mui/components';
import { CustomKeywords, CustomPeople } from '@/mui/components/CustomIcon';

import styles from './CreateResetPassword.module.scss';

function CreateResetPassword() {
  const dispatch = useDispatch();
  const router = useRouter();
  const email = useSelector(emailSelector);
  const password = useSelector(passwordSelector);
  const password2 = useSelector(password2Selector);
  const isFormLoading = useSelector(isFormLoadingSelector);
  const [passwordError, setPasswordError] = useState('');
  const [showPassword, togglePassword] = useState(false);

  const isCreatePage = router.route === CREATE_PASSWORD_PAGE.path;

  useEffect(() => {
    dispatch(
      verifyCodeAction({
        token: router.query.token,
      }),
    );
  }, []);

  const disabledSubmit = isFormLoading || !password || !password2;

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

    if (password !== password2) {
      setPasswordError('Passwords don`t match!');
    } else if (!passwordRegExp.test(password)) {
      setPasswordError(
        'Password does not meet password policy. ' +
          'Use at least 8 characters and a mix of upper/lowercase letters, numbers, and symbols',
      );
    } else {
      dispatch(submitPasswordAction());
    }
  };

  return (
    <Layout
      title={isCreatePage ? 'Create password' : 'Reset password'}
      firstSection={
        <Stack component="form" disabled={disabledSubmit} onSubmit={onSubmit} spacing={3} fullWidth>
          <Stack spacing={2}>
            <TextField
              data-id="email"
              variant="outlined"
              fullWidth
              type="email"
              placeholder="Email"
              autoComplete="username"
              value={email}
              disabled
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <CustomPeople />
                  </InputAdornment>
                ),
              }}
            />

            <TextField
              data-id="password"
              type={showPassword ? 'text' : 'password'}
              fullWidth
              variant="outlined"
              placeholder="New Password"
              error={!!passwordError}
              disabled={isFormLoading}
              value={password}
              onChange={({ target }) => dispatch(setFieldAction({ password: target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <CustomKeywords />
                  </InputAdornment>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => togglePassword((e) => !e)}>
                      {showPassword ? <VisibilityOffRounded /> : <VisibilityRounded />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <TextField
              data-id="password2"
              type={showPassword ? 'text' : 'password'}
              fullWidth
              variant="outlined"
              placeholder="Re-enter Password"
              error={!!passwordError}
              helperText={passwordError}
              disabled={isFormLoading}
              value={password2}
              FormHelperTextProps={{
                classes: {
                  root: styles.HelperText,
                },
              }}
              onChange={({ target }) => dispatch(setFieldAction({ password2: target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <CustomKeywords />
                  </InputAdornment>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => togglePassword((e) => !e)}>
                      {showPassword ? <VisibilityOffRounded /> : <VisibilityRounded />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </Stack>
          <div>
            <Button
              type="submit"
              data-id="reset-submit"
              variant="contained"
              color="primary"
              disabled={disabledSubmit}
              size="large"
              shape="circular"
            >
              {isCreatePage ? 'Create Password' : 'Reset Password'}
            </Button>
          </div>
        </Stack>
      }
    />
  );
}

export default CreateResetPassword;
