import React, {useState, useEffect} from "react";
import { useLocation } from "react-router-dom";
import usersService from '../services/UsersService'

import SignUp from "../components/AuthPages/SignUp/index2";
import LoadingSpinner from '../components/Spinners/LoadingSpinner'
import AuthLayout from '../components/AuthPages/AuthLayout2'

function PromoRefer() {
  const api = new usersService()

  const location = useLocation();

  const queryParams = new URLSearchParams(location?.search);
  const refer_link = queryParams.get("refer_link")?.toUpperCase();

  const [reload, setReload] = useState(false)

  let [details, setDetails] = useState({loading:true, error:false, data:{}})

  useEffect(()=>{
    setDetails({loading:true, error:false, data:{}})
    if(refer_link){
      const reqData = {
        refer_link: refer_link,
        path: 'promoref'
      }
      api.loadRefer(reqData).then(res => {
        if(res?.data?.internal_return < 0){
          return setDetails({loading:false, error:true, data:{}})
        }
        setDetails({loading:false, error:false, data:res.data})
      }).catch(err => {
        setDetails({loading:false, error:true, data:{}})
      })
    }else{
      setDetails({loading:false, error:false, data:{}})
    }
  },[reload])
  return (
    <>
    {details.loading ?
      <LoadingSpinner size="32" color="sky-blue" height="h-screen" />
    : details.error ?
      <AuthLayout>
        <ErrorComponent onClick={()=>setReload(prev => !prev)} />
      </AuthLayout>
    :
      <SignUp details={details.data} />
    }
    </>
  );
}

export default PromoRefer;


const ErrorComponent = ({ onClick }) => (
  <div className="input-area">
    <div className="my-5">
      <p className="text-[14px] leading-[19px] text-center text-[#181c32]">
        This error occurs because you have already verified this link or the
        link has expired. Try login or reset password. If none worked, try to
        create the account from the start.
      </p>
    </div>

    <div className="signin-area flex justify-center mb-3.5">
      <button
        onClick={onClick}
        type="button"
        className={`rounded-[0.475rem] mb-6 text-[15px] font-semibold text-[#009ef7] hover:text-white flex justify-center bg-[#f1faff] hover:bg-[#009ef7] transition-all duration-300 items-center py-[0.8875rem] px-[1.81rem]`}
      >
        <span>Try Again</span>
      </button>
    </div>
  </div>
);
