"use client";
import React, { useEffect, useState } from "react";
import { RewardTiersModal } from "../components/rewards/RewardModal";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { useRouter } from "next/navigation";
import {
  fetchWeeklyBonus,
  fetchReckBack,
  fetchRewardPacks,
  fetchRewards,
} from "../lib/api/rewards";
import AlertModal from "../components/ui/AlertModal";
import NotAvailable from "../components/ui/NotAvailable";

const Inner = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const [isRewardModalOpen, setIsRewardModalOpen] = useState(false);
  const [rewardLoading, setRewardLoading] = useState(false);
  const [weeklyBonusLoading, setWeeklyBonusLoading] = useState(false);
  const [rakeLoading, setRakeLoading] = useState(false);
  const [packsLoading, setPacksLoading] = useState(false);
  const user = useSelector((state: any) => state.auth.user) as User | null;
  const [rewardsData, setRewardsData] = useState<any>(null);

  const authFucntion = () => {
    if (!user?.userId || !user?.token) {
      setModalType("error");
      setModalMsg("Please log in to play game.");
      setModalOpen(true);
      return;
    }
  };

  const errorModalHandler = (message: string) => {
    setModalType("error");
    setModalMsg(message);
    setModalOpen(true);
  };

  const successModalHandler = (message: string) => {
    setModalType("success");
    setModalMsg(message);
    setModalOpen(true);
  };

  const getRewards = async () => {
    authFucntion();
    setRewardLoading(true);
    try {
      const res = await fetchRewards(user?.userId, user?.token);
      console.log("res", res);
      setRewardsData(res);
      if (res.resp === "success") {
        successModalHandler("Rewards fetched successfully!");
      }
      setRewardLoading(false);
    } catch (e: any) {
      errorModalHandler(e.message);
      setRewardLoading(false);
      console.error("Error fetching rewards:", e);
    }
  };

  const getRewardPacks = async () => {
    authFucntion();
    if (rewardsData?.claimed_packs === 0) {
      errorModalHandler("No reward packs available to claim");
      return;
    }
    setPacksLoading(true);
    try {
      const res = await fetchRewardPacks(user?.userId, user?.token);
      if (res.resp === "success") {
        successModalHandler("Reward pack claimed successfully!");
      } else {
        errorModalHandler(res.msg);
      }
      setPacksLoading(false);
    } catch (e: any) {
      errorModalHandler(e?.message || "Something went wrong");
      setPacksLoading(false);
    }
  };

  const getReckBack = async () => {
    authFucntion();
    setRakeLoading(true);
    if (rewardsData?.reckback === 0) {
      errorModalHandler("No rakeback available to claim");
      setRakeLoading(false);
      return;
    }
    try {
      const res = await fetchReckBack(user?.userId, user?.token);
      if (res.resp === "success") {
        successModalHandler("Rakeback claimed successfully!");
      } else {
        errorModalHandler(res.msg);
      }
      setRakeLoading(false);
    } catch (e: any) {
      setRakeLoading(false);
      errorModalHandler(e?.message || "Something went wrong");
    }
  };

  const getWeeklyBonus = async () => {
    authFucntion();
    if (rewardsData?.weekly_obnus === 0) {
      errorModalHandler("No weekly bonus available to claim");
      return;
    }
    setWeeklyBonusLoading(true);
    try {
      const res = await fetchWeeklyBonus(user?.userId, user?.token);
      if (res.resp === "success") {
        successModalHandler("Weekly bonus claimed successfully!");
      } else {
        errorModalHandler(res.msg);
      }
      setWeeklyBonusLoading(false);
    } catch (e: any) {
      errorModalHandler(e?.message || "Something went wrong");
    }
  };

  useEffect(() => {
    getRewards();
  }, []);
  return (
    <div className="min-h-screen bg-black text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          {/* Header */}
          <div className=" z-10">
            <div className="container mx-auto py-4">
              {/* <div className="flex items-center gap-4">
            <button
              // onClick={() => setIsOpenCardModal(true)}
              className="cursor-pointer text-xs md:text-sm p-2 px-4 font-extrabold text-white bg-[var(--color-gray)] hover:text-white italic font-sofia transition"
            >
              &lt; BACK
            </button>
            <h1 className="text-sm md:text-base font-extrabold italic tracking-tighter">
              REWARDS
            </h1>
          </div> */}
              <div className="bg-[#161E2A] overflow-hidden scrollbar-hide p-5 mt-4 flex items-center flex-col md:flex-row gap-4 justify-between w-full">
                <div className="flex flex-col gap-3">
                  <h1 className="font-sofia italic font-bold text-base md:text-2xl 2xl:text-2xl">
                    Free Monthly packs
                  </h1>
                  <p className="text-[#54657E] font-sofia text-sm md:text-lg 2xl:text-2xl">
                    5 packs earned
                  </p>
                  <div className="flex items-center gap-1.5">
                    <div className="bg-[#FF348D] w-[19px] h-1.5"></div>
                    <div className="bg-[#FF348D] w-4.75 h-1.5"></div>

                    <div className="bg-[#FF348D] w-[19px] h-1.5"></div>

                    <div className="bg-[#FF348D] w-[19px] h-1.5"></div>
                  </div>
                  <button
                    onClick={() => getRewardPacks()}
                    className="bg-[#4D4CFE] mt-5 font-onest font-semibold text-xs md:text-sm 2xl:text-base py-2 px-10 "
                  >
                    {packsLoading ? "LOADING..." : "CLAIM REWARD"}
                  </button>
                </div>
                <div className="flex relative  -mb-14 items-center">
                  <div className="absolute bottom-17 left-1/2 -translate-x-1/2 w-[150px] md:w-[470px] h-[200px] md:h-[250px] bg-[var(--color-blue)] blur-3xl rounded-full opacity-50"></div>
                  <img
                    src="/images/roll/left.webp"
                    className="w-24 md:w-40.75 object-contain relative z-10 -mr-5 h-[236px]"
                    alt=""
                  />
                  <img
                    src="/images/roll/center.webp"
                    className="w-24 md:w-[163px] object-contain relative z-20 h-[298px]"
                    alt=""
                  />

                  <img
                    src="/images/roll/right.webp"
                    className="w-24 md:w-[163px] object-contain -ml-5 relative z-10 h-[236px]"
                    alt=""
                  />
                </div>
              </div>

              <div className="flex w-full flex-col md:flex-row items-center gap-4">
                <div className="bg-[#161E2A] w-full flex-1 p-5 mt-4 flex-col flex">
                  <div className="flex items-center flex-col md:flex-row justify-between gap-3">
                    <div className="">
                      <h1 className="uppercase md:text-left mb-3 md:mb-0 text-center font-sofia italic font-bold text-base md:text-2xl 2xl:text-2xl">
                        weekly bonus
                      </h1>
                      <div className="flex items-center gap-2">
                        <span className="bg-[#2B5AFF26] px-7 font-sofia md:text-base 2xl:text-base font-bold text-sm py-1 ">
                          LEVEL {user?.level.lavel}
                        </span>
                        <p className="text-[#54657E] font-semibold font-sofia">
                          100% BUY BACK
                        </p>
                        <img
                          onClick={() => setIsRewardModalOpen(true)}
                          src="/images/roll/i.svg"
                          alt=""
                        />
                      </div>
                    </div>
                    <div className="bg-[#121924] font-sofia items-center p-4 flex flex-col">
                      <p className="font-semibold italic text-xs md:text-sm 2xl:text-base">
                        BUYBACK TODAY
                      </p>
                      {rewardLoading ? (
                        <div className="flex w-full h-7 items-center justify-center">
                          <div className="w-5 h-5 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                        </div>
                      ) : (
                        <h1 className="text-sm flex items-center gap-1 md:text-2xl 2xl:text-3xl font-extrabold">
                          {user?.activeMode === "coins" ? (
                            <img
                              src="/images/header/win.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          ) : (
                            <img
                              src="/images/header/star.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          )}{" "}
                          {rewardsData?.weekly_obnus}
                        </h1>
                      )}
                    </div>
                  </div>
                  <button
                    onClick={() => getWeeklyBonus()}
                    className="md:w-fit bg-[#4D4CFE] mt-8 cursor-pointer font-onest font-semibold text-xs md:text-sm 2xl:text-base py-2 px-10 "
                  >
                    {weeklyBonusLoading ? "LOADING..." : "CLAIM REWARD"}
                  </button>
                </div>
                <div className="bg-[#161E2A] w-full flex-1 p-5 mt-4 flex-col flex">
                  <div className="flex items-center flex-col md:flex-row justify-between gap-3">
                    <div className="">
                      <h1 className="uppercase md:text-left mb-3 md:mb-0 text-center font-sofia italic font-bold text-base md:text-2xl 2xl:text-2xl">
                        rakeback
                      </h1>
                      <div className="flex items-center gap-2">
                        <span className="bg-[#2B5AFF26] px-7 font-sofia md:text-base 2xl:text-base font-bold text-sm py-1 ">
                          LEVEL {user?.level.lavel}
                        </span>
                        <p className="text-[#54657E] font-semibold font-sofia">
                          100% BUY BACK
                        </p>
                        <img
                          onClick={() => setIsRewardModalOpen(true)}
                          src="/images/roll/i.svg"
                          alt=""
                        />
                      </div>
                    </div>
                    <div className="bg-[#121924] font-sofia items-center p-4 flex flex-col">
                      <p className="font-semibold italic text-xs md:text-sm 2xl:text-base">
                        BUYBACK TODAY
                      </p>
                      {rewardLoading ? (
                        <div className="flex w-full h-7 items-center justify-center">
                          <div className="w-5 h-5 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                        </div>
                      ) : (
                        <h1 className="text-sm flex items-center gap-1 md:text-2xl 2xl:text-3xl font-extrabold">
                          {user?.activeMode === "coins" ? (
                            <img
                              src="/images/header/win.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          ) : (
                            <img
                              src="/images/header/star.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          )}
                          {rewardsData?.reckback}
                        </h1>
                      )}
                    </div>
                  </div>
                  <button
                    onClick={() => getReckBack()}
                    className="bg-[#4D4CFE] cursor-pointer md:w-fit mt-8 font-onest font-semibold text-xs md:text-sm 2xl:text-base py-2 px-10 "
                  >
                    {rakeLoading ? "LOADING..." : "CLAIM REWARD"}
                  </button>
                </div>
              </div>
            </div>
          </div>
          <AlertModal
            open={modalOpen}
            type={modalType}
            message={modalMsg}
            onClose={() => setModalOpen(false)}
          />
          <RewardTiersModal
            isOpen={isRewardModalOpen}
            onClose={() => setIsRewardModalOpen(false)}
          />
        </>
      )}
    </div>
  );
};

export default Inner;
