import { useEffect, useState } from 'react';
import { IoIosEyeOff, IoIosEye } from 'react-icons/io';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { RxCross2 } from 'react-icons/rx';
import { defaultSetting, signUp } from '../../redux/_reducers/_reducers';
import settings from '../../domainConfig';
import LoginSlider from '../../component/signup/LoginSlider';
import { VscReferences } from 'react-icons/vsc';
import { FaCopy, FaRegCopy } from 'react-icons/fa';
import CopyToClipboard from 'react-copy-to-clipboard';

const Register = ({ 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 { refferId } = useParams();
  const [referralCode, setReferralCode] = useState(refferId || '');
  const [clipboardText, setClipboardText] = useState("");
  const { defaultSettingData, signup_loading } = useSelector((state) => state.authentication);


  useEffect(() => {
    dispatch(defaultSetting());
  }, [dispatch])

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

  const handleUsernameChange = (e) => {
    const value = e.target.value;
    setUsername(value);
    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}$/;
    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;
    if (/^\d{0,10}$/.test(value)) {
      setMobileNumber(value);
      if (value.length === 10) {
        setErrors((prevErrors) => {
          const newErrors = { ...prevErrors };
          delete newErrors.mobileNumber;
          return newErrors;
        });
      }
    }
  };

  const handleOnChange = (e) => {
    const { name, value } = e.target;
    let truncatedValue = value;
    if (name === "mobileNo") {
      // Truncate value to 10 digits if it exceeds
      if (value.length > 10) {

        return setErrors({ ...errors, mobileNo: "Mobile number must be 10 digits" })
      }
      truncatedValue = value.slice(0, 10);
    }
    if (name === "referralCode") {
      setReferralCode(value);
      setClipboardText(e.target.value);
    }
    setUser({ ...user, [name]: truncatedValue });
    setErrors({ ...errors, [name]: "" }); // Clear errors when the input changes
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleOnSubmit(e);
    }
  };

  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?.value}.com`,
        mobile: mobileNumber,
        password: password,
        confirmpassword: password,
        referral_code: referralCode,
      };

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

  const copyToClipboard = () => {
    if (referralCode.trim() !== "") {
      copy(referralCode);
      alert("Referral Code Copied!");
    }
  };

  return (
    <div className='lg:w-[40%] w-full mx-auto'>
      {/* <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 lg:mt-[50px] h-[calc(100%-50px)] overflow-y-auto overflow-x-hidden' 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='Login Logo' />
        </div>
        <LoginSlider />

        <div className='flex flex-col gap-2 mt-8'>
          <label className='text-[#525252]'>Username</label>
          <input
            type='text'
            className='bg-white 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-white text-sm rounded-md p-3 divide-x divide-gray-500'>
            <div className='flex gap-2 justify-center items-center'>
              <img src="/India_flag.png" className="h-7" />
              <span>+91</span>
            </div>
            <input
              type='text'
              className=' w-full border-0 outline-none h-full bg-white 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-white text-sm rounded-md'>
            <input
              type={showPassword ? 'text' : 'password'}
              className='p-3 w-full bg-white 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 gap-2 mt-4 ">
          <div className="py-2.5 text-black">
            <VscReferences size={20} />
          </div>
          <div className="w-full pb-2">
            <input
              type="text"
              name="referralCode"
              id="referralCode"
              value={referralCode}
              className="py-2  text-sm text-black bg-transparent placeholder-gray-500 focus:outline-none border-b-2 border-gray-400 focus:border-[#f36c21] w-full"
              placeholder="Referral Code Optional"
              onChange={handleOnChange}
              onKeyPress={handleKeyPress}
            />
          </div>

        </div> */}


        <div className="flex gap-2 mt-4 items-center">
          <div className="py-2.5 text-black">
            <VscReferences size={20} />
          </div>
          <div className="w-full pb-2 relative">
            <input
              type="text"
              name="referralCode"
              id="referralCode"
              value={referralCode}
              className="py-2 text-sm text-black bg-transparent placeholder-gray-500 focus:outline-none border-b-2 border-gray-400 focus:border-[#f36c21] w-full"
              placeholder="Referral Code Optional"
              onChange={handleOnChange}
            />
            <CopyToClipboard text={clipboardText}>
              <button
                className="absolute right-0 top-1/2 -translate-y-1/2 py-2.5 px-4 rounded-md flex space-x-2 transition"
              >
                <FaCopy size={15} color="black" />
              </button>
            </CopyToClipboard>
          </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 className='flex justify-center items-center text-[15px] mt-4 text-[#9b9b9b] gap-2'>
          Already a member ?  <span onClick={() => { navigate('/dashboard') }} className='text-primary cursor-pointer'>Log in</span>
        </div>
      </form>
    </div>
  );
};

export default Register;