import { useEffect, useRef, useState } from "react";
import SignUp from "../signup/SignUp";
import { useNavigate, useParams } from "react-router-dom";
import { BiMenuAltLeft } from "react-icons/bi";
import { useDispatch, useSelector } from "react-redux";
import { defaultSetting, walletBalance } from "../../redux/_reducers/_reducers";
import Login from "../login/Login";
import { LuCircleUser } from "react-icons/lu";
import { IoWalletOutline } from "react-icons/io5";
import { TfiReload } from "react-icons/tfi";
import ResetPassword from "../resetPassword/ResetPassword";
import settings from "../../domainConfig";
import CopyReferCode from "../../views/copyReferCode/CopyReferCode";
import { TbMessage } from "react-icons/tb";
import DashboardModal from "../dashboardModal/DashboardModal";
import { FaAndroid } from "react-icons/fa";
import LiveChat from "../LiveChat/LiveChat";
import LanguageModal from "../languageModal/LanguageModal";
import Turnover from '../Turnover/Turnover';
import DepositWithdrawl from "../depositWithdrawlModal/DepositWithdrawl";


function AppHeader() {
  const token = JSON.parse(localStorage?.getItem("token"));
  const navigate = useNavigate();
  const [balance, setBalance] = useState({
    coins: "",
    exposure: "",
    profitLoss: ""
  });
  const dropdownRef = useRef(null)
  const dispatch = useDispatch();
  const [toggleLogin, setToggleLogin] = useState(false);
  const [toggleSignUp, setToggleSignUp] = useState(false);
  const [togglePassword, setTogglePassword] = useState(false);
  const [toggleRefer, setToggleRefer] = useState(false);
  const [isRotating, setIsRotating] = useState(false);
  const [turnover, setTurnOver] = useState(false);
  const [depositwithdraw, setDepositWithdraw] = useState(false);

  const [showLiveChat, setShowLiveChat] = useState(false);

  const [showModal, setShowModal] = useState(true);
  const [showLanguage, setShowLanguage] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (token) {
      setShowModal(false);
    }
  }, []);

  const handleWithdrawalClick = () => {
    setIsRotating(true);

    setTimeout(() => {
      setIsRotating(false);
    }, 1000);
    dispatch(walletBalance())
  };

  const handleReferClose = () => {
    setToggleRefer(false);
  }

  const handlePasswordclose = () => {
    setTogglePassword(false);
  }

  useEffect(() => {
    walletBalance();
  }, [balance])

  const handleClickOutside = (event) => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
      setShowMainSelect(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const [balanceRotate, setBalanceRotate] = useState(false);
  const handleBalanceClick = () => {
    setBalanceRotate(true);
    setTimeout(() => {
      setBalanceRotate(false);
    }, 1000);
  };


  const handleReferModal = () => {
    setToggleRefer((prev) => !prev);
    setTogglePassword(false);
    setToggleLogin(false);
    setToggleSignUp(false);
    setShowMainSelect(false);
  };

  const handleTurnOverModal = () => {
    setTurnOver((prev) => !prev)
    setToggleRefer(false);
    setTogglePassword(false);
    setToggleLogin(false);
    setToggleSignUp(false);
    setShowMainSelect(false);
  };

  const handleDWModal = () => {
    setDepositWithdraw((prev) => !prev)
    setTurnOver(false)
    setToggleRefer(false);
    setTogglePassword(false);
    setToggleLogin(false);
    setToggleSignUp(false);
    setShowMainSelect(false);
  };

  const handleResetPassword = () => {
    setTogglePassword((prev) => !prev);
    setToggleLogin(false);
    setToggleSignUp(false);
    setShowMainSelect(false);
  };

  const handleLogin = () => {
    setToggleLogin((prev) => !prev);
    setToggleSignUp(false);
  };

  const { defaultSettingData } = useSelector((state) => state.authentication);
  const handleSignUp = () => {
    setToggleSignUp((prev) => !prev);
    setToggleLogin(false);
  };

  const handleLanguage = () => {
    setShowLanguage((prev) => !prev);
    setToggleSignUp(false);
    setToggleLogin(false);
  };

  const handleToggle = () => {
    document.body.classList.toggle("sidebar-collapse");
  };

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

  const [showMainSelect, setShowMainSelect] = useState(false);

  const handleSMainSelect = () => {
    setShowMainSelect((prev) => !prev);
  };

  useEffect(() => {
    setTimeout(() => {
      let Balance = JSON.parse(localStorage.getItem("clientBalance"));
      let clientExposure = JSON.parse(localStorage.getItem("clientExposure"));
      let clientProfitLoss = JSON.parse(localStorage.getItem("clientProfitLoss"));
      setBalance({
        coins: Balance,
        exposure: clientExposure,
        profitLoss: clientProfitLoss
      });
    }, 1000);
  }, [balance]);

  const SELECT_LIST = {
    payments: [
      {
        name: "Deposit",
        img: "/headerImages/deposit.png",
        // onClick: () => {
        //   navigate(`/deposit`)
        //   setShowMainSelect(false)
        // },
        onClick: handleDWModal,
      },
      {
        name: "Withdrawal",
        img: "/headerImages/withdrawal.png",
        // onClick: () => {
        //   navigate(`/withdrawal`)
        //   setShowMainSelect(false)
        // },
        onClick: handleDWModal,
      },
      {
        name: "Balance Transfer",
        img: "/headerImages/icon-bt.png",
        onClick: () => {
          navigate(`/balance-transfer`)
          setShowMainSelect(false)
        },
      },
      {
        name: "Turnover",
        img: "/headerImages/icon-turnover.png",
        onClick: handleTurnOverModal
      },
    ],

    record: [
      {
        name: "Betting Records",
        img: "/headerImages/records.png",
        onClick: () => {
          navigate(`/bet-history`)
          setShowMainSelect(false)
        },
      },
      {
        name: "Pending Bets",
        img: "/headerImages/records.png",
        onClick: () => {
          navigate(`/pending-bets`)
          setShowMainSelect(false)
        },
      },
      {
        name: "Account Statements",
        img: "/headerImages/bank.png",
        onClick: () => {
          navigate(`/account-statement`)
          setShowMainSelect(false)
        },
      },

      // {
      //   name: "Transaction Records",
      //   img: "/headerImages/bet-records.png",
      //   onClick: () => {
      //     navigate(`/deposit-withdraw`)
      //     setShowMainSelect(false)
      //   },
      // },
    ],

    personalInfo: [
      {
        name: "Personal Info",
        img: "/headerImages/icon-profile.png",
        onClick: () => {
          navigate(`/profile`)
          setShowMainSelect(false)
        },
      },
      {
        name: "Refer Bonus",
        img: "/headerImages/icon-referral.png",
        onClick: handleReferModal,
      },
      {
        name: "Reset Password",
        img: "/headerImages/resetpasswords.png",
        onClick: handleResetPassword,
      },
      {
        name: "Profit & Loss",
        img: "/headerImages/inbox.png",
        onClick: () => {
          navigate(`/profit-loss`)
          setShowMainSelect(false)
        },
      },


    ],

    bank: [
      {
        name: "Transaction Records",
        img: "/headerImages/bet-records.png",
        onClick: () => {
          navigate(`/deposit-withdraw`)
          setShowMainSelect(false)
        },
      },
      // {
      //   name: "Bank Statements",
      //   img: "/headerImages/bank.png",
      //   onClick: () => {
      //     navigate(`/account-statement`)
      //     setShowMainSelect(false)
      //   },
      // },
    ],
  };
  const LogoImg = defaultSettingData?.find((item) => item.key === "site.LOGO")?.value;
  const dashboardPopup = defaultSettingData?.find((data) => data?.key === "site.welcome_popup");

  const handleLiveChat = () => {
    setShowLiveChat((prev) => !prev);
  };

  return (
    <div className=" max-w-[1200px] flex h-full w-full justify-between items-center px-2">

      {showLiveChat && (
        <div className="fixed inset-0 backdrop-blur-[3px]  z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)]  border  text-black   rounded-md"
          >
            <LiveChat setShowLiveChat={setShowLiveChat} />
          </div>
        </div>
      )}

      <BiMenuAltLeft
        className="block lg:hidden text-white"
        onClick={handleToggle}
        size={40}
      />

      <div className="w-full flex md:justify-center justify-between items-center lg:justify-start">
        {/* ${LogoImg} */}
        <div></div>
        <img onClick={() => { navigate('/dashboard') }} src={`${settings.IMAGE_URL}${LogoImg}`} className="h-[50px] cursor-pointer transition-all ease-in-out duration-500"></img>
        <div className="flex gap-2 items-center">

          <div className="flex flex-col justify-end items-center -space-y-[2px] md:hidden">
            <FaAndroid className="text-white" size={22} />
            <p className="text-[12px] font-semibold text-white">Android</p>
          </div>

          <div className="flex flex-col justify-end items-center -space-y-[2px] md:hidden" onClick={() => handleLiveChat()}>
            <TbMessage className="text-white" size={22} />
            <p className="text-[12px] font-semibold text-white">Live Chat</p>
          </div>
        </div>
      </div>

      {!token && (
        <div className="lg:flex hidden justify-end items-center gap-1.5 w-full">
          <button
            className="py-1.5 text-white px-10 bg-[var(--light-header)] rounded-md text-[14px] whitespace-nowrap"
            onClick={() => {
              handleLogin();
            }}
          >
            Login
          </button>
          <button
            className="py-1.5 text-white px-8 bg-[#64cc2f] rounded-md text-[14px] whitespace-nowrap"
            onClick={() => {
              handleSignUp();
            }}
          >
            Sign up
          </button>
          <div
            onClick={() => {
              handleLanguage();
            }}
            className="cursor-pointer flex justify-center items-center hover:opacity-80 ">
            <img src="/footer_images/IN.png" className="w-[32px] h-[32px] " />
          </div>
        </div>
      )}

      {token && (
        <div className="relative md:flex hidden justify-end items-center gap-[15px] w-full">
          <button
            // onClick={() => { navigate('/deposit') }} 
            onClick={() => {
              handleDWModal();
            }}
            className="py-1.5 px-3 bg-[var(--light-header)] text-white rounded-md text-[14px] whitespace-nowrap flex justify-center items-center gap-2 ">
            <IoWalletOutline className="text-white" size={16} />
            Deposit
          </button>
          <button onClick={handleWithdrawalClick} className="py-1.5 px-3 bg-[#64cc2f] text-white rounded-md text-[14px] whitespace-nowrap flex justify-center items-center gap-4">
            <TfiReload className={`transition-transform duration-1000 ${isRotating ? "rotate-animation" : ""}`} size={14} />
            Main Wallet &#8377;{balance?.coins}
          </button>
          <style >

            {
              `@keyframes rotate {
              0% { transform: rotate(0deg); }
              100% { transform: rotate(360deg); }
            }
            
            .rotate-animation {
              animation: rotate 1s linear;
            }`
            }

          </style>
          <div className="flex justify-center items-center gap-1">
            <LuCircleUser
              className="text-white cursor-pointer"
              size={44}
              onClick={() => {
                handleSMainSelect();
              }}
            />
            <div
              onClick={() => {
                handleLanguage();
              }}
              className="w-full cursor-pointer flex justify-center items-center hover:opacity-80 ">
              <img src="/footer_images/IN.png" className="w-[30px] h-[30px] " />
            </div>
          </div>

          {showMainSelect && (
            <div
              ref={dropdownRef}
              className={` transition-all  ease-in-out duration-1000 absolute w-[220px] max-h-[510px] lg:h-[calc(100vh-100px)] h-[calc(92vh-80px)] px-3 py-2 overflow-y-auto  bg-white -right-10 top-12 rounded-md z-[20]`}
              style={{ boxShadow: '5px 1px 10px  rgb(201,197,197)' }}
            >

              <div className="flex flex-col  w-full text-black text-[14px] font-thin">
                Exposure
                <span className="flex text-red-700  gap-1 text-[18px] font-bold items-center">
                  {balance?.exposure} <TfiReload className={`transition-transform duration-1000 cursor-pointer ${balanceRotate ? "rotate-animation" : ""}`} onClick={() => { handleBalanceClick() }} size={10} />{" "}
                </span>
              </div>
              <div className="flex flex-col mt-7 gap-4">
                {SELECT_LIST?.payments?.map((element) => {
                  return (
                    <div
                      onClick={element?.onClick}
                      className="flex justify-start items-center w-full text-[#555555]  font-bold gap-4 cursor-pointer">
                      <img src={element?.img} className="h-8" />
                      {element?.name}
                    </div>
                  );
                })}
              </div>

              <div className="flex flex-col mt-7 gap-4">
                {SELECT_LIST?.record?.map((element) => {
                  return (
                    <div
                      onClick={element?.onClick}
                      className="flex justify-start items-center w-full text-[#555555] font-bold gap-4 cursor-pointer">
                      <img src={element?.img} className="h-8" />
                      {element?.name}
                    </div>
                  );
                })}
              </div>

              <div className="flex flex-col mt-7 gap-4">
                {SELECT_LIST?.personalInfo?.map((element) => {
                  return (
                    <div
                      onClick={element?.onClick}
                      className="flex justify-start items-center w-full text-[#555555] font-bold gap-4 cursor-pointer">
                      <img src={element?.img} className="h-8" />
                      {element?.name}
                    </div>
                  );
                })}
              </div>

              <div className="flex flex-col mt-7 gap-4">
                {SELECT_LIST?.bank?.map((element) => {
                  return (
                    <div
                      onClick={element?.onClick}
                      className="flex justify-start items-center w-full text-[#555555] font-bold gap-4 cursor-pointer">
                      <img src={element?.img} className="h-8" />
                      {element?.name}
                    </div>
                  );
                })}
              </div>

              <div className="flex flex-col mt-7 gap-4">
                <div onClick={() => {
                  localStorage.clear();
                  window.location.reload();
                }}
                  className="flex justify-start items-center w-full text-[#555555] font-bold gap-4 cursor-pointer">
                  <img src="/headerImages/logout.png" className="h-8" />
                  Log Out
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* <button className=" md:block hidden bg-[#64cc2f] rounded-full text-[14px] ml-4 ">
        <img src="/India_flag.png" alt="" className="h-6 w-8  " />
      </button> */}

      <div className="flex gap-2">
        {/* {token && <div className="flex flex-col md:hidden  ">
          <img src="/headerImages/appdownload.svg" className="h-5 "></img>
          <span className="whitespace-nowrap text-[12px] text-white font-bold">
            App
          </span>
        </div>} */}
        {/* <div className="flex flex-col md:hidden  ">
          <img alt="" src="/headerImages/livechat.svg" className="h-5 "></img>
          <span className="whitespace-nowrap text-[12px] text-white font-bold">
            Live Chat
          </span>
        </div> */}
      </div>

      {toggleLogin && (
        <div className="fixed inset-0 backdrop-blur-[3px]  z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)]  border  text-black   rounded-md"
          >
            <Login handleLogin={handleLogin} handleSignUp={handleSignUp} />
          </div>
        </div>
      )}

      {toggleSignUp && (
        <div className="fixed inset-0 backdrop-blur-[3px] z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white relative  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)]   border  text-black   rounded-md"
          >
            <SignUp handleSignUp={handleSignUp} handleLogin={handleLogin} />
          </div>
        </div>
      )}

      {togglePassword && (
        <div className="fixed inset-0 backdrop-blur-[3px]  z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)]  border text-black   rounded-md"
          >
            <ResetPassword handleSignUp={handleSignUp} handleLogin={handleLogin} handleResetPassword={handleResetPassword} handleClose={handlePasswordclose} setTogglePassword={setTogglePassword} />
          </div>
        </div>
      )}

      {turnover && (
        <div className="fixed inset-0 backdrop-blur-[3px]  z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)]  border text-black   rounded-md"
          >
            <Turnover handleClose={handleTurnOverModal} />
          </div>
        </div>
      )}

      {depositwithdraw && (
        <div className="fixed inset-0 backdrop-blur-[3px]  z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white  w-full h-full md:max-w-[700px] md:w-[370px] md:h-[calc(100vh-16rem)] overflow-y-auto  border text-black   rounded-md"
          >
            <DepositWithdrawl handleClose={handleDWModal} />
          </div>
        </div>
      )}

      {toggleRefer && (
        <div className="fixed inset-0 backdrop-blur-[6px] z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white border text-black px-5 rounded-md"
          >
            <CopyReferCode handleSignUp={handleSignUp} handleLogin={handleLogin} handleReferModal={handleReferModal} handleRefer={handleReferClose} setToggleRefer={setToggleRefer} />
          </div>
        </div>
      )}

      {dashboardPopup?.value && showModal ? (
        <div className="fixed inset-0 backdrop-blur-[6px] z-50 bg-transparent flex justify-center items-center">
          <div
            onClick={(e) => e.stopPropagation()}
            className=" animate-slideInFromBottom  !bg-white border text-black px-5 rounded-md"
          >
            <DashboardModal setShowModal={setShowModal} />
          </div>
        </div>
      ) : null}

      {showLanguage && (
        <LanguageModal handleLanguage={handleLanguage} />
      )}

    </div>
  );
}

export default AppHeader;