import Image from "next/image";
import React from "react";
import { ImageConstant } from "../../../constant/ImageConstant";
import { Button } from "../ui/button";
import {
  useDeleteSubscription,
  useGetSubScriptionCoinList,
  useGetSubScriptionList,
  usePurchaseCoin,
  useSubscriptionCoin,
} from "@/state/profile/profile.action";
import { useSession } from "next-auth/react";
interface RefillCoinBoxProps {
  onRefetch: () => void;
}
const RefillCoinBox: React.FC<RefillCoinBoxProps> = ({ onRefetch }) => {
  const { data: session } = useSession();
  const { data: subscriptionData, refetch: refetchSubscription } =
    useGetSubScriptionList(!!session?.user?.id);
  const { data: subscriptionCoinData } = useGetSubScriptionCoinList();
  const stopUnlock = usePurchaseCoin();
  const getSubscription = useSubscriptionCoin();

  const handlePurchase = (coinAmount: string) => {
    stopUnlock.mutate(
      { coinPackId: coinAmount },
      {
        onSuccess: () => onRefetch(),
      }
    );
  };
  const handleClick = (id: string | number) => {
    getSubscription.mutate(
      { subscriptionId: id },
      {
        onSuccess: () => onRefetch(),
      }
    );
  };
  console.log("subscriptionData", subscriptionData);
  const { mutate: deleteSubscription } = useDeleteSubscription();
  const handelCancelSubscription = () => {
    deleteSubscription("", {
      onSuccess: () => {
        refetchSubscription();
      },
      onError: (error: Error) => {
        console.error("Error cancelling subscription:", error.message);
      },
    });
  };

  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-12 gap-6 bg-[#1A1A1A] p-5 rounded-[12px] mb-5 items-center">
        <div className="md:col-span-7">
          {subscriptionData?.map((item) => {
            // Check the subscription status

            return (
              <div key={item.id} className="mb-5">
                {item.subscriptionStatus === "cancelled" && (
                  <p className="mb-5 text-white  text-2xl font-semibold text-left">
                    Your subscription is canceled
                  </p>
                )}
                <div
                  className="flex gap-8 py-5 px-2 rounded-2xl bg-no-repeat justify-center items-center"
                  style={{
                    background: `url(${ImageConstant.refillCoinBg.src})`,
                    backgroundRepeat: "no-repeat",
                    backgroundSize: "cover",
                  }}
                >
                  <Image src={ImageConstant.crown} alt="" />

                  <div>
                    <h2 className="text-[20px] text-[#773700] font-bold">
                      {item.subscription_name}
                    </h2>
                    <p className="text-[18px] text-[#773700]">
                      {item.description}
                    </p>
                  </div>

                  {/* Show Active tag if subscribed */}
                  {item.isSubscribed === true && (
                    <span className="bg-green-600 text-white px-4 py-1 rounded-md text-sm font-semibold">
                      Active
                    </span>
                  )}

                  {/* Show purchase button if not subscribed */}
                  {item.isSubscribed === false && (
                    <Button
                      onClick={() => handleClick(item.subscription_id)}
                      className="px-8 bg-[#773700] cursor-pointer text-white"
                    >
                      ${item.price}
                    </Button>
                  )}
                </div>

                {/* Cancel or canceled message */}
                {item.subscriptionStatus === "active" && (
                  <Button
                    onClick={handelCancelSubscription}
                    className="mt-5 border border-[#E50914] bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E] text-[14px] text-white cursor-pointer p-[24px_30px] hover:!bg-white flex items-center justify-center gap-2"
                  >
                    Cancel Subscription
                  </Button>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-12 gap-4">
        {subscriptionCoinData?.map((item, index) => (
          <div key={index} className="md:col-span-3 m-2">
            <div
              className="border border-gray-500 relative rounded-2xl cursor-pointer hover:scale-105 transition-transform"
              onClick={() => handlePurchase(item?.id)}
            >
              <h4 className="rounded-tr-lg rounded-bl-lg p-1 px-2 border-[#E50914] bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E] text-[18px] font-bold absolute top-0 right-0">
                {item.discountPercentage}%
              </h4>
              <div className="p-4 mt-4">
                <h5 className="flex gap-2 text-[28px] items-center justify-center">
                  <Image
                    src={ImageConstant.coin}
                    alt=""
                    width={30}
                    height={30}
                  />
                  <span className="opacity-50">{item.coins}</span>
                </h5>
                <h6 className="flex gap-2 text-[28px] items-center justify-center">
                  +{item.bonus_coins}
                </h6>
              </div>
              <p className="bg-[#484848] text-[20px] text-center p-2 rounded-b-2xl">
                ${item.price_in_dollars_stripe}
              </p>
            </div>
          </div>
        ))}
      </div>
      <h5 className="text-white text-[18px] my-5">Tips</h5>
      <div className="text-[16px] opacity-60 ">
        <p className="mb-2">
          1. StoryBox offers both free and paid content. You can choose what to
          unlock.
        </p>
        <p className="mb-2">
          2. Reward Coins can be earned through tasks and top-up bonuses and can
          be used like regular Coins to unlock episodes.
        </p>
        <p className="mb-2">
          3. Reward Coins will expire and are used first when unlocking content.
        </p>
        <p className="mb-2">
          4. Privilege: Enjoy unlimited access to StoryBox series during
          subscription.
        </p>
        <p className="mb-2">
          5. Activation: Subscriptions activate within 24 hours of purchase,
          pending approval from Google Play.
        </p>
        <p className="mb-2">
          6. Auto-Renewal: Subscriptions auto-renew at the original price,
          charged 24 hours before each period, unless canceled.
        </p>
        <p className="mb-2">
          7. Cancellation: If you want to unsubscribe, please proceed to your
          Google Play account and cancel your subscription at least 24 hours
          before the end of your current subscription period.
        </p>
      </div>
    </>
  );
};

export default RefillCoinBox;
