import { VisibilityOffOutlined, VisibilityOutlined } from '@mui/icons-material';
import { LoadingButton } from '@mui/lab';
import {
  Box,
  Grid,
  IconButton,
  InputLabel,
  Link,
  TextField,
  Typography,
} from '@mui/material';
import { useFormik } from 'formik';
import React, { useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import * as Yup from 'yup';
import { initializeMessaging } from '../../config/firebase';
import { NOTIFICATION } from '../../constants';
import { pushNotification } from '../../utils/notification';
import {
  passwordLengthRegex,
  passwordLetterRegex,
  passwordNumberRegex,
  passwordSpacesRegex,
} from '../../utils/regex';
import { requestNotificationPermission } from '../Notifications/notificationUtils';
import { resetFormData } from '../Signup/signupAction';
import PasswordValidation from './component/PasswordValidation';
import { login, profile } from './loginAction';
import { useStyles } from './loginStyles';

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

function LoginForm() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const defaultFormData = useRef({ email: '', password: '' });
  const classes = useStyles();
  const [showPassword, setShowPassword] = useState(false);

  const fieldRefs = {
    email: useRef(null),
    password: useRef(null),
  };

  const handleTogglePasswordVisibility = () => {
    setShowPassword((prevShowPassword) => !prevShowPassword);
  };

  const handleSubmit = async (values, formik) => {
    try {
      // Dispatch login action and wait for it to complete
      const loginResp = await dispatch(login(values));
      
      // Dispatch profile action separately and don't wait for it
      await dispatch(profile());
      
      // Reset form data
      await dispatch(resetFormData());
      
      // Show success notification
      pushNotification('Login successful', NOTIFICATION.SUCCESS);
      // Navigate to dashboard immediately without waiting for profile
      navigate('/');
    } catch (error) {
      console.error('Login error:', error);
      
      // Handle errors in a more robust way
      let errorMessage = 'Login failed. Please try again.';
      
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
        
        if (errorMessage.includes('Password')) {
          fieldRefs.password.current.focus();
          formik.setErrors({
            password: errorMessage,
            email: '',
          });
        } else {
          fieldRefs.email.current.focus();
          formik.setErrors({
            email: errorMessage,
            password: '',
          });
        }
      } else {
        // Generic error handling
        pushNotification(errorMessage, NOTIFICATION.ERROR);
      }
    } finally {
      formik.setSubmitting(false);
    }
  };

  const handleForgotClick = () => {
    navigate('/auth/forgotpassword');
  };

  const formik = useFormik({
    initialValues: defaultFormData.current,
    validationSchema,
    onSubmit: (values) => handleSubmit(values, formik),
  });

  const handleSubmitClick = async (e) => {
    e.preventDefault();
    // 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 (
    <Box className={classes.right}>
      <Typography variant="Inter-Bold" className={classes.heading}>
        Hello!
      </Typography>
      <Typography variant="Inter-Medium" className={classes.collageName}>
        Welcome to 24x7 AI HealthCare Receptionist
      </Typography>
      <Grid container spacing={2} className={classes.gridContainer} margin={0}>
        <Grid item xs={6} className={classes.loginGridItem}>
          Login
        </Grid>
        <Grid
          item
          xs={6}
          className={classes.signupGridItem}
          onClick={() => navigate('/auth/signup/your-details')}
        >
          Sign Up
        </Grid>
      </Grid>
      <form onSubmit={handleSubmitClick} className={classes.form}>
        <Box className={classes.formBody}>
          <InputLabel
            shrink={false}
            htmlFor={'email'}
            className={classes.labelStyle}
          >
            <Typography className={classes.inputTitle}>Email</Typography>
          </InputLabel>
          <TextField
            className={classes.emailField}
            color="secondary"
            placeholder="Enter Email ID"
            variant="outlined"
            margin="normal"
            fullWidth
            name="email"
            value={formik.values.email}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            inputRef={fieldRefs.email}
            error={Boolean(formik.errors.email && formik.touched.email)}
            helperText={
              formik.errors.email && formik.touched.email
                ? formik.errors.email
                : ''
            }
          />
          <InputLabel
            shrink={false}
            htmlFor={'password'}
            className={classes.labelStyle}
          >
            <Typography className={classes.inputTitle}>Password</Typography>
          </InputLabel>

          <TextField
            color="secondary"
            placeholder="Enter Password"
            variant="outlined"
            margin="normal"
            fullWidth
            type={showPassword ? 'text' : 'password'}
            name="password"
            value={formik.values.password}
            onChange={formik.handleChange}
            onBlur={(e) => {
              formik.handleBlur(e);
            }}
            inputRef={fieldRefs.password}
            error={Boolean(formik.errors.password && formik.touched.password)}
            helperText={
              formik.errors.password && formik.touched.password
                ? formik.errors.password
                : ''
            }
            InputProps={{
              endAdornment: (
                <IconButton onClick={handleTogglePasswordVisibility} edge="end">
                  {!showPassword ? (
                    <VisibilityOffOutlined />
                  ) : (
                    <VisibilityOutlined />
                  )}
                </IconButton>
              ),
            }}
          />

          {/* Password validation display */}
          {!formik.isValid && (
            <>
              <Typography className={classes.passwordCheckListTitle}>
                Note: Password must be
              </Typography>
              <Box className={classes.passwordCheckList}>
                <PasswordValidation
                  isValid={passwordLengthRegex.test(formik.values.password)}
                  text="at least 8 characters"
                />
                <PasswordValidation
                  isValid={passwordLetterRegex.test(formik.values.password)}
                  text="at least 1 letter"
                />
                <PasswordValidation
                  isValid={passwordNumberRegex.test(formik.values.password)}
                  text="at least 1 number"
                />
                <PasswordValidation
                  isValid={passwordSpacesRegex.test(formik.values.password)}
                  text="with no spaces"
                />
              </Box>
            </>
          )}
        </Box>

        <Box>
          <LoadingButton
            className={classes.loginButton}
            size="large"
            type="submit"
            variant="contained"
            loading={formik.isSubmitting}
          >
            Login
          </LoadingButton>
          <Box className={classes.actions}>
            <Link
              size="small"
              className={classes.forgotPasswordButton}
              onClick={handleForgotClick}
            >
              Forgot Password
              <span className={classes.linkWithLine}></span>
            </Link>
          </Box>
        </Box>
      </form>
    </Box>
  );
}

export default LoginForm;
