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

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

  const { defaultSettingData, signup_loading } = useSelector((state) => state.authentication);
  const SiteTitle = defaultSettingData?.find((item) => item.key === "site.TITLE")?.value;
  const LogoImg = defaultSettingData?.find((item) => item.key === "site.LOGO")?.value;


  const [selectedCurrency, setSelectedCurrency] = useState("INR");
  const [countryCode, setCountryCode] = useState("+91");
  const [flag, setFlag] = useState("/India_flag.png");

  const handleCurrencyChange = (event) => {
    const currency = event.target.value;
    setSelectedCurrency(currency);
    if (currency === "INR") {
      setCountryCode("+91");
      // setFlag("/India_flag.png");
    } else {
      setCountryCode("+880");
      // setFlag("/BD.png");
    }
  };

  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);
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%#]{6,20}$/;
    // Remove error when input becomes valid (allowing 6-20 characters)
    if (value && value.length >= 6 && value.length <= 20 && !/\s/.test(value) && passwordRegex.test(password)) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors.password;
        return newErrors;
      });
    }
  };

  const handleMobileNumberChange = (e) => {
    const value = e.target.value;
    // Ensure only numeric input and limit to 10 digits
    if (/^\d{0,10}$/.test(value)) {
      setMobileNumber(value);
      if (value.length === 10) {
        setErrors((prevErrors) => {
          const newErrors = { ...prevErrors };
          delete newErrors.mobileNumber;
          return newErrors;
        });
      }
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (signup_loading) return
    const validationErrors = {};

    if (!username || username.length < 4 || /\s/.test(username)) {
      validationErrors.username = 'Username must be 4-5 characters, no spaces allowed.';
    }
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%#]{6,20}$/;

    if (!password || password.length < 6 || password.length > 20 || /\s/.test(password) || !passwordRegex.test(password)) {
      validationErrors.password = 'Password must be 6-20 characters, contain at least one letter and one number, and may contain special characters (@$!%#).';
    }

    if (!mobileNumber || mobileNumber.length !== 10) {
      validationErrors.mobileNumber = 'Mobile number must be a 10-digit number.';
    }

    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
    } else {
      const data = {
        name: username,
        username: username,
        email: `${username}@${SiteTitle}.com`,
        mobile: mobileNumber,
        password: password,
        confirmpassword: password,
        referral_code: ''
      };

      dispatch(signUp(data)).then((response) => {
        if (!response.error && response) {
          setUsername("");
          setPassword("");
          setMobileNumber("");
          setErrors({});
          handleSignUp();
        }
      });
    }
  };

  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>
        SignUp
        <RxCross2 className='text-white cursor-pointer' onClick={() => handleSignUp()} />
      </div>
      <form className='px-3 mt-[50px] h-[calc(100%-50px)] overflow-y-auto overflow-x-hidden pb-4' onSubmit={handleSubmit}>
        <div className='mt-[5px] flex flex-col gap-3 justify-center items-center'>
          <img src={`${settings.IMAGE_URL}${LogoImg}`} className='h-[50px]' alt='Signup Logo' />
        </div>
        <LoginSlider />

        <div className="flex flex-col gap-2 mt-4">
          <label className="text-[#525252]">Choose Currency</label>
          <select
            value={selectedCurrency}
            onChange={handleCurrencyChange}
            className="bg-[#eeeeee] text-sm rounded-md p-3 border-0 outline-none cursor-pointer">
            <option value="INR">🇮🇳 INR</option>
            <option value="BDT">🇧🇩 BDT</option>
          </select>
        </div>

        <div className='flex flex-col gap-2 mt-4'>
          <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]'>Mobile Number</label>
          <div className='flex gap-4 items-center bg-[#eeeeee] text-sm rounded-md p-3 divide-x divide-gray-500'>
            <div className='flex gap-2 justify-center items-center'>
              {/* <img src={flag} className="h-7" /> */}
              <span>{countryCode}</span>
            </div>
            <input
              type='text'
              className=' w-full border-0 outline-none h-full bg-transparent px-2'
              placeholder='Phone number'
              value={mobileNumber}
              onChange={handleMobileNumberChange}
              maxLength={10}  // Limit to 10 digits
            />
          </div>
          {errors.mobileNumber && <div className="text-red-500 text-xs">{errors.mobileNumber}</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>

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

        <div onClick={() => handleLogin()} className='flex justify-center items-center text-[15px] mt-4 text-[#9b9b9b] gap-2'>
          Already a member ?  <span className='text-primary cursor-pointer'>Log in</span>
        </div>
      </form>
    </>
  );
};

export default SignUp;
