import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { emailRegExp } from '@/modules/@common/constants/validation';

import { isFormLoadingSelector } from '@/modules/auth/common/redux/selectors';
import { resetPasswordEventAction } from '@/modules/auth/Login/redux/slices';

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

function ForgotPassword() {
  const dispatch = useDispatch();
  const [email, setEmail] = useState('');
  const isFormLoading = useSelector(isFormLoadingSelector);
  const [error, setError] = useState(false);
  const [message, setMessage] = useState('');
  const [isDisableControllers, disableControllers] = useState(false);

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

    const emailTrimmed = email.trim();

    setEmail(emailTrimmed);

    if (!emailTrimmed) {
      setError(true);
      setMessage('The email cannot be empty');
    } else if (!emailRegExp.test(emailTrimmed)) {
      setError(true);
      setMessage('The email you entered is incorrect');
    } else {
      setError(false);
      setMessage('If your email is valid you will be sent a reset password link');
      dispatch(
        resetPasswordEventAction({
          email: emailTrimmed,
        }),
      );
      disableControllers(true);
    }
  };

  return (
    <Layout
      title="Forgot Password"
      subTitle={message}
      firstSection={
        <Stack
          component="form"
          disabled={isFormLoading || isDisableControllers}
          onSubmit={onSubmit}
          spacing={3}
          fullWidth
        >
          <TextField
            data-id="email"
            type="email"
            variant="outlined"
            placeholder="Email"
            error={error}
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            disabled={isFormLoading || isDisableControllers}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <CustomPeople />
                </InputAdornment>
              ),
            }}
          />
          <div>
            <Button
              type="submit"
              data-id="reset-submit"
              variant="contained"
              color="primary"
              disabled={isFormLoading || isDisableControllers}
              size="large"
              shape="circular"
            >
              Reset Password
            </Button>
          </div>
        </Stack>
      }
    />
  );
}

export default ForgotPassword;
