/* eslint-disable react/prop-types */
import { useState } from "react";
import { IoIosEyeOff, IoIosEye } from "react-icons/io";
import { useDispatch, useSelector } from "react-redux";
import { login } from "../../redux/_reducers/_reducers";
import { useNavigate } from "react-router-dom";
import { RxCross2 } from "react-icons/rx";
import settings from "../../domainConfig";

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 { defaultSettingData, login_loading } = useSelector(state => state.authentication);

  const LogoImg = defaultSettingData?.find((item) => item.key === "site.LOGO")?.value;

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

    // Remove error when input becomes valid
    if (value && value.length >= 4 && value.length <= 5 && !/\s/.test(value)) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.username;
        return newErrors;
      });
    }
  };

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

    // Remove error when input becomes valid
    if (value && value.length >= 6 && value.length <= 20 && !/\s/.test(value)) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.password;
        return newErrors;
      });
    }
  };

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

    if (login_loading) return
    const validationErrors = {};

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

    if (
      !password ||
      password.length < 6 ||
      password.length > 20 ||
      /\s/.test(password)
    ) {
      validationErrors.password =
        "Password must be 6-20 characters, no spaces allowed.";
    }

    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();

          const stakes = "100,500,1000,5000,10000,50000,100000";
          localStorage.setItem("match_stack", stakes);

        }
      });
    }
  };

  return (
    <>
      <div className="h-[50px] absolute flex justify-between text-white text-[19px] rounded-tr-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 mt-[50px] h-[calc(100%-50px)] overflow-y-auto "
        onSubmit={handleSubmit}
      >
        <div className="mt-10 flex flex-col gap-3 justify-center items-center">
          <img
            src={`${settings.IMAGE_URL}${LogoImg}`}
            className="h-[60px]"
            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"
              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>
          )}
        </div>

        {/* <div className='flex mt-1.5 justify-end'>
          <div className='text-[var(--primary)]  text-[15px]'>Forgot Password?</div>
        </div> */}

        <button
          type="submit"
          disabled={(!username && !password)}
          className={`w-full py-3 mt-5 rounded-md ${username && 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_loading ? <div className="loaderNewLogin"></div> : "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 cursor-pointer">
            Sign Up
          </span>
        </div>
      </form>
    </>
  );
};

export default Login;
