import React, { useRef } from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import CustomModal from '../Modal/Modal';
import { Box, TextField } from '@mui/material';
import { useStyles } from './userStyles';
import { updateUserEmailAndContact } from '../../services/users.services';
import { pushNotification } from '../../utils/notification';
import { NOTIFICATION } from '../../constants';

function UserInfoPopup({ handleCancel, handleSubmit }) {
  const classes = useStyles();

  const fieldRefs = {
    name: useRef(null),
    mobile: useRef(null),
  };

  // Define validation schema using Yup
  const validationSchema = Yup.object({
    name: Yup.string().required('User Name is required'),
    mobile: Yup.string()
      .min(10, 'Enter a valid 10-digit mobile number')
      .required('Mobile number is required'),
  });

  // Initialize Formik
  const formik = useFormik({
    initialValues: {
      name: '',
      mobile: '',
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      // Handle form submission here
      updateDetails(values);
    },
  });

  const updateDetails = async (values) => {
    try {
      const response = await updateUserEmailAndContact(values);
      if (response.status === 200) {
        handleSubmit();
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error(error);
    }
  };

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

    if (errors.length) {
      // Find the first invalid field and focus it
      const firstErrorField = errors[0];
      const firstErrorRef = fieldRefs[firstErrorField]?.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(formikErrors[firstErrorField], NOTIFICATION.ERROR);
    }

    formik.handleSubmit();
  };

  return (
    <CustomModal
      noPadding
      showFooter
      footerRightButtonTitle="Save"
      onFooterLeftButtonClick={handleCancel}
      onFooterRightButtonClick={handleSubmitClick}
      title={'Add Details'}
      isTitleLeft={true}
      modalBodyFunction={() => (
        <Box
          sx={{
            '& .MuiDialogContent-root': {
              padding: '0px',
            },
          }}
        >
          <form className={classes.form} onSubmit={formik.handleSubmit}>
            <TextField
              className={classes.userName}
              color="secondary"
              placeholder="User Name"
              variant="outlined"
              margin="normal"
              fullWidth
              name="name"
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={(e) => {
                formik.setFieldValue('name', e.target.value.trim());
                formik.handleBlur(e);
              }}
              inputRef={fieldRefs.name}
              error={Boolean(formik.errors.name && formik.touched.name)}
              helperText={
                formik.errors.name && formik.touched.name ? (
                  <span className={classes.errorMessage}>
                    <i>{formik.errors.name}</i>
                  </span>
                ) : (
                  ''
                )
              }
            />
            <TextField
              className={classes.phoneNumberField}
              color="secondary"
              placeholder="Enter 10-Digits mobile number"
              variant="outlined"
              margin="normal"
              fullWidth
              name="mobile"
              value={formik.values.mobile}
              onChange={(e) => {
                if (e.target.value?.length <= 10) {
                  const value = e.target.value?.match(/\d+/g) || '';
                  formik.setFieldValue('mobile', value?.toString());
                }
              }}
              onBlur={formik.handleBlur}
              inputRef={fieldRefs.mobile}
              error={Boolean(formik.errors.mobile && formik.touched.mobile)}
              helperText={
                formik.errors.mobile && formik.touched.mobile ? (
                  <span className={classes.errorMessage}>
                    <i>{formik.errors.mobile}</i>
                  </span>
                ) : (
                  ''
                )
              }
              inputProps={{
                type: 'text',
                pattern: '[0-9]*',
                autocomplete: 'off',
              }}
            />
          </form>
        </Box>
      )}
    />
  );
}

export default UserInfoPopup;
