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 { getPasswordLessAuthAction } 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 UserPasswordError() {
  const dispatch = useDispatch();
  const isFormLoading = useSelector(isFormLoadingSelector);
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

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

    const emailTrimmed = email.trim();

    if (!emailTrimmed) {
      setError('The email cannot be empty');
    } else if (!emailRegExp.test(emailTrimmed)) {
      setError('The email you entered is incorrect');
    } else {
      dispatch(
        getPasswordLessAuthAction({
          email: emailTrimmed,
        }),
      );
    }
  };

  return (
    <Layout
      title="Sign in with one-time password"
      subTitle="We will send it to the user email below"
      firstSection={
        <Stack component="form" disabled={isFormLoading} onSubmit={onSubmit} spacing={3} fullWidth>
          <TextField
            data-id="email"
            type="email"
            variant="outlined"
            placeholder="Email"
            value={email}
            disabled={isFormLoading}
            error={!!error}
            helperText={error || null}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <CustomPeople />
                </InputAdornment>
              ),
            }}
            onChange={(event) => setEmail(event.target.value)}
            onFocus={() => setError('')}
          />
          <div>
            <Button
              data-id="reset-submit"
              variant="contained"
              color="primary"
              disabled={isFormLoading}
              size="large"
              shape="circular"
              type="submit"
            >
              Continue
            </Button>
          </div>
        </Stack>
      }
    />
  );
}

export default UserPasswordError;
