import { useState } from 'react';
import { IoIosEyeOff, IoIosEye } from 'react-icons/io';
import { useDispatch } from 'react-redux';
import { login } from '../../redux/_reducers/_reducers';
import { useNavigate } from 'react-router-dom';
import { RxCross2 } from 'react-icons/rx';

const Login = ({ handleLogin, handleSignUp }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState({});
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleUsernameChange = (e) => {
    const value = e.target.value;
    setUsername(value);

    // Username validation
    if (value && value.length >= 4  && !/\s/.test(value)) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.username;  // Remove error if valid
        return newErrors;
      });
    } else if (value === '') {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.username;  // Clear error when empty
        return newErrors;
      });
    } else {
      setErrors((prevErrors) => ({
        ...prevErrors,
        username: 'Username must be 4 characters, no spaces allowed.',
      }));
    }
  };

  const handlePasswordChange = (e) => {
    const value = e.target.value;
    setPassword(value);

    // Regular expression to check the password validity
    const handlePasswordChange = (e) => {
      const value = e.target.value;
      setPassword(value);
    
      // Updated password validation regex
      // const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%#]{6,20}$/;
    
      // Remove error when input becomes valid
     if (value) {
        setErrors((prevErrors) => ({
          ...prevErrors,
          password: 'Password must be 6-20 characters, must contain at least one English letter and one number, and may contain special characters (@$!%#).',
        }));
      } else {
        setErrors((prevErrors) => {
          const newErrors = { ...prevErrors };
          delete newErrors.password;
          return newErrors;
        });
      }
    };
    

    if (value === '') {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.password;  
        return newErrors;
      });
    } else if (passwordRegex.test(value)) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.password;  
        return newErrors;
      });
    } else {
      setErrors((prevErrors) => ({
        ...prevErrors,
        password: 'Password must be 6-20 characters, contain at least one letter and one number, and may contain special characters (@$!%#).',
      }));
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const validationErrors = {};

    // Username validation
    if (!username || username.length < 4 || /\s/.test(username)) {
      validationErrors.username = 'Username must be 4-5 characters, no spaces allowed.';
    }

    // Password validation will be handled during input change, so no need to check again here.
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
    } else {
  
      const data = {
        "user_name": username,
        "password": password
      };

      dispatch(login(data)).then((response) => {
        if (response && response?.payload?.userinfo) {
          setUsername("");
          setPassword("");
          setErrors({});
          handleLogin();
        }
      });
    }
  };

  return (
    <div className='w-full bg-transparent md:rounded-md'>
      <div className='flex justify-between text-white text-[19px] md:rounded-tr-md md:rounded-tl-md w-full items-center bg-[var(--primary)]  py-[10px] px-2'>
        <div></div>
        Login
        <RxCross2 className='text-white cursor-pointer' onClick={() => handleLogin()} />
      </div>
      <form className='px-3' onSubmit={handleSubmit}>
        <div className='mt-20 flex flex-col gap-3 justify-center items-center'>
          <img src='/loginImages/loginlogo.png' className='h-[36px]' alt='Login Logo' />
        </div>

        <div className='flex flex-col gap-2 mt-8'>
          <label className='text-[#525252]'>Username</label>
          <input
            type='text'
            className='bg-[#eeeeee] text-sm rounded-md p-3 border-0 outline-none'
            placeholder='4-5 char, allow numbers, no space'
            value={username}
            onChange={handleUsernameChange}
          />
          {errors.username && <div className="text-red-500 text-xs">{errors.username}</div>}
        </div>

        <div className='flex flex-col gap-2 mt-4'>
          <label className='text-[#525252]'>Password</label>
          <div className='flex justify-center items-center pr-2 bg-[#eeeeee] text-sm rounded-md'>
            <input
              type={showPassword ? 'text' : 'password'}
              className={`p-3 w-full bg-[#eeeeee] border-0 outline-none ${errors.password ? 'border-red-500' : ''}`} // Only apply red border if error exists
              placeholder='6-20 characters and Numbers'
              value={password}
              onChange={handlePasswordChange}
            />
            {showPassword ? (
              <IoIosEye
                size={20}
                className='text-[#9b9b9b] cursor-pointer'
                onClick={() => setShowPassword(!showPassword)}
              />
            ) : (
              <IoIosEyeOff
                size={20}
                className='text-[#9b9b9b] cursor-pointer'
                onClick={() => setShowPassword(!showPassword)}
              />
            )}
          </div>
          {errors.password && <div className="text-red-500 text-xs">{errors.password}</div>} {/* Only show error if condition is not met */}
        </div>

        <button
          type='submit'
          disabled={!username || !password || errors.username || errors.password}
          className={`w-full py-3 mt-5 rounded-md ${(username && password && !errors.username && !errors.password) ? 'bg-gradient-to-r from-[#82d856] to-[#5ab72a] via-[#5ab72a] bg-[length:200%_100%] bg-[position:left] text-white' : "bg-[#999999] text-[#c2c2c2]"}`}
        >
          Login
        </button>

        <div className='flex justify-center items-center text-[15px] mt-4 text-[#9b9b9b] gap-2'>
          Do not have an account? <span onClick={() => handleSignUp()} className='text-primary'>Sign Up</span>
        </div>
      </form>
    </div>
  );
};

export default Login;
