import { LoadingButton } from '@mui/lab';
import { Box, InputLabel, TextField, Typography } from '@mui/material';
import { useFormik } from 'formik';
import { useRef } from 'react';
import * as Yup from 'yup';
import { NOTIFICATION } from '../../constants';
import { forgotPassword } from '../../services/auth.services';
import { pushNotification } from '../../utils/notification';
import { useStyles } from './forgotPasswordStyles';

const validationSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid Email Address')
    .required('Email is required'),
});

function ForgotPasswordForm({ onSubmit, setEmail }) {
  const classes = useStyles();

  const emailRef = useRef(null);

  const formik = useFormik({
    initialValues: { email: '' },
    validationSchema,
    onSubmit: async (values) => {
      try {
        const response = await forgotPassword(values);
        if (response.status === 200) {
          // setTimer(15);
          setEmail(values.email);
          // setShowButton(false);
          pushNotification(response?.data?.message, NOTIFICATION.SUCCESS);
          onSubmit();
        }
      } catch (error) {
        if (error.response?.data?.message) {
          formik.setErrors({
            email: error?.response?.data?.message,
          });
          emailRef.current.focus();
        }
      } finally {
        formik.setSubmitting(false);
      }
    },
  });

  const handleSubmitClick = async (e) => {
    e.preventDefault();
    const formikError = await formik.validateForm();
    const errors = Object.keys(formikError);

    if (errors.length) {
      // Find the first invalid field and focus it
      const firstErrorField = errors[0];
      const firstErrorRef = emailRef?.current;

      if (firstErrorRef) {
        // Scroll to the first invalid field smoothly
        if (typeof firstErrorRef?.scrollIntoView === 'function') {
          firstErrorRef?.scrollIntoView({
            behavior: 'smooth',
            block: 'center',
          });
        }

        // Focus the field after a slight delay (to ensure scrolling completes first)
        setTimeout(() => firstErrorRef.focus(), 300);
      }

      // Show error notification
      if (formik?.touched[firstErrorField])
        pushNotification(formikError[firstErrorField], NOTIFICATION.ERROR);
    }

    formik.handleSubmit();
  };

  return (
    <Box className={classes.right}>
      <form onSubmit={handleSubmitClick} className={classes.form}>
        <Box className={classes.formBody}>
          <Box className={classes.formHeader}>
            <Typography className={classes.subHeading}>
              Please provide the email address that you used when you signed up
              for your account.
            </Typography>
          </Box>
          <InputLabel
            shrink={false}
            htmlFor={'email'}
            className={classes.labelStyle}
          >
            <Typography
              className={classes.inputTitle}
              style={{
                fontSize: '0.8rem',
              }}
            >
              Email Address*
            </Typography>
          </InputLabel>
          <TextField
            style={{ marginTop: '2px' }}
            color="secondary"
            placeholder="Enter Email ID"
            variant="outlined"
            margin="normal"
            fullWidth
            name="email"
            value={formik.values.email}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            inputRef={emailRef}
            error={Boolean(formik.errors.email && formik.touched.email)}
            helperText={
              formik.errors.email && formik.touched.email
                ? formik.errors.email
                : ''
            }
          />
        </Box>
        {/* )} */}
        <Typography className={classes.sendEmailText}>
          We will send you an email that will allow you to reset your password.
        </Typography>
        <LoadingButton
          size="large"
          type="submit"
          variant="contained"
          className={classes.submitButton}
          loading={formik.isSubmitting}
        >
          Reset Password
        </LoadingButton>
        {/* <Box className={classes.formFooter}>
          <Typography className={classes.emailText}>
            If you no longer have access to this email account, please contact
            our support team at
          </Typography>
          <Typography className={classes.emailText}>
            <a href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a>
          </Typography>
        </Box> */}
      </form>
    </Box>
  );
}

export default ForgotPasswordForm;
