import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import Image from 'next/image'
import edit from '@/assets/images/editButton.png'
import { useQuery } from "@tanstack/react-query";
import { ManageSubscriptionAPI, PaymentSubScriptionsAPI, PlanAPI, SelfAPI, SubscriptionLinkAPI } from "@/Utils/APIRequest/Endpoints";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import ActivePlan from "./ActivePlan";
import Loader from "@/Layout/Loader";
import ActivePlanModal from "./BrandActivePlanModal";
import { useDispatch, useSelector } from "react-redux";
import { AppStore } from "@/lib/store";
import { CustomToast } from "@/Utils/CustomToast";
import { formatNumber } from "@/Utils/Other/FormateNumbers";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import usePost from "@/Utils/Hooks/usePost";
import { getUserDetails } from "@/lib/Features/UserDetails/userDetails";
import ConfirmationModal from "@/Component/Common/Modal/ConfirmationModal";
import { LoaderSVG } from "@/Component/Common/SVGs/CommonSVG";
import RedirectionLoader from "./RedirectionLoader";
import { useSearchParams } from "next/navigation";

const PlanListing = (props) => {
    const { role, setPremiumModal, listRefetch, planTab, setMainModal, planData } = props
    const { translations } = useTranslation();
    const [modal, setModal] = useState(null);
    const [freeModal, setFreeModal] = useState(null);
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const [currentPlan, setCurrentPlan] = useState<any>(null);
    const [upcomingPlan, setUpcomingPlan] = useState<any>(null);
    const [loadingPlanId, setLoadingPlanId] = useState(null);
    const [paymentConfirmLoader, setPaymentConfirmLoader] = useState(false);
    const dispatch = useDispatch();
    const queryParams = useSearchParams();
    const sessionId = queryParams.get("session_id");
    const [manageSub, setManageSub] = useState(false);


    // API GET
    const { data: PlanAPIData, isPending, refetch } = useQuery({ queryKey: [PlanAPI], queryFn: () => CustomFetch({ url: PlanAPI, params: { status: role == "brand" ? 1 : -1 } }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data })

    const { data: UserData, refetch: selfRefetch, isPending: selfLoader, fetchStatus } = useQuery({
        queryKey: [SelfAPI], queryFn: () => CustomFetch({ url: SelfAPI }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data
    });

    // const { isPending: subscriptionLoader, mutate } = usePost(PaymentSubScriptionsAPI, null, (response) => {
    //     if (response.status == 200 || response.status == 201) {
    //         console.log("response >>>> plan list", response);

    //         let obj: any = {
    //             ...userDetails, is_subscribed: true
    //         }
    //         dispatch(getUserDetails({ ...obj }))
    //         CustomToast("success", translations?.subscribedSuccessfully)
    //         refetch();
    //         listRefetch();
    //         setFreeModal(null);
    //     }
    // }, null)

    const { isPending: subscriptionLoader, mutate: linkMutate } = usePost(SubscriptionLinkAPI, null, (response) => {
        if (response.status == 200 || response.status == 201) {
            console.log("response >>>> plan list", response);
            window.location.href = response?.data?.link;
            setLoadingPlanId(null);
        }
    }, null)

    const { data: ManageAPIData, isPending: manageLoader, refetch: manageRefetch } = useQuery({ queryKey: [ManageSubscriptionAPI], queryFn: () => CustomFetch({ url: ManageSubscriptionAPI }, null, false), refetchOnWindowFocus: false, enabled: manageSub, select: (data) => data?.data })

    useEffect(() => {
        if (ManageAPIData) {
            window.location.href = ManageAPIData?.url;
            setManageSub(false);
        }
    }, [ManageAPIData])


    useEffect(() => {
        setCurrentPlan(planData?.activatedSubscription || null)
        setUpcomingPlan(planData?.upcomingSubscription || null);
    }, [planData])

    // Properly typed ref
    const listRef = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
        if (listRef.current) {
            const titles = listRef.current.querySelectorAll("h5");
            const titleArray = Array.from(titles) as HTMLElement[];
            let maxHeight = 0;
            titleArray.forEach((title) => {
                maxHeight = Math.max(maxHeight, title.offsetHeight);
            });

            // Apply the maximum height to all <h5> elements
            titleArray.forEach((title) => {
                title.style.height = `${maxHeight}px`;
            });
        }
    }, [PlanAPIData]);

    useEffect(() => {
        if (sessionId) {
            setPaymentConfirmLoader(true);
            setTimeout(() => {
                selfRefetch();
                refetch();
                setPaymentConfirmLoader(false);
                CustomToast("success", "Payment Successful");
            }, 9000);

            setTimeout(() => {
                window.history.replaceState({}, document.title, window.location.pathname);
            }, 10000)
        }
    }, [sessionId])

    const freePlanID = PlanAPIData?.find((elem) => elem?.plan_type == "free")?.id;

    const isCurrentPlan = (plan) => {
        if (plan?.plan_type === "free") {
            return currentPlan?.plan?.plan_type === "free";
        }
        return (
            currentPlan?.plan?.id === plan?.id &&
            currentPlan?.interval === planTab
        );
    };

    const isUpcomingPlan = (plan) => {
        if (plan?.plan_type === "free") {
            return upcomingPlan?.plan?.plan_type === "free";
        }
        return (
            upcomingPlan?.plan?.id === plan?.id &&
            upcomingPlan?.interval === planTab
        );
    };

    const getButtonText = (plan) => {
        // 1. If this is the current plan
        // if (isCurrentPlan(plan)) return "Current Plan";
        if (currentPlan?.plan?.id === plan?.id) {
            return "Current Plan";
        }
        // 2. If this is the upcoming plan
        // if (isUpcomingPlan(plan)) return "Upcoming Plan";
        if (upcomingPlan?.plan?.id === plan?.id) {
            return "Upcoming Plan";
        }

        // 3. Handle upgrades/downgrades between intervals for the same plan_type
        // if (
        //     plan?.id === currentPlan?.plan?.id &&
        //     planTab !== currentPlan?.interval
        // ) {
        //     // e.g. switching between monthly/yearly of same plan
        //     return planTab === "year" ? "Switch to Yearly" : "Switch to Monthly";
        // }

        // 5. If not subscribed to this plan (or it's an upgrade/downgrade)
        // Show "Get {plan.name}" dynamically
        return `Get ${plan?.name}`;
    };


    const handlePlanButtonClick = (elem) => {
        if (currentPlan?.plan?.id === elem?.id) {
            setManageSub(true);
        } else if (isUpcomingPlan(elem)) {
            setManageSub(true);
        } else {
            setLoadingPlanId(elem?.id);
            // Continue with existing logic for activation
            // const selectedInterval = elem?.plan_type === "free" ? "month" : planTab;
            // const planDataToSet = { ...elem, interval: selectedInterval };
            // elem?.plan_type === "free" ? setFreeModal(planDataToSet) : setModal(planDataToSet);
            let obj: any = {
                "plan_id": elem?.id,
                "interval": planTab
            }
            linkMutate(obj);
        }
    };

    const callbackFunction = (planID) => {
        const obj: any = {
            "plan_id": freePlanID,
            "interval": "month"
        }
        // mutate(obj);
    }

    const formatPrice = (price, opts: { forceTwoDecimals?: boolean } = {}) => {
        const num = Number(price ?? 0);
        if (Number.isNaN(num)) return price;
        if (opts.forceTwoDecimals) return num.toFixed(1);
        return num.toString().replace(/\.00$/, '');
    };


    if (isPending || selfLoader) {
        return <Loader />
    }

    return (
        <>
            {(subscriptionLoader || paymentConfirmLoader || manageSub) && <RedirectionLoader sessionId={sessionId} />}
            <div ref={listRef} className="md:w-2/2 flex flex-col md:flex-row gap-5 flex-wrap justify-center">
                {
                    PlanAPIData?.length > 0 ?
                        PlanAPIData?.map((elem) => {
                            const isFreePlan = elem?.name?.toLowerCase().includes("free");
                            const isYearlyView = planTab === "year" && !isFreePlan;
                            const yearlyMonthlyPrice = isYearlyView ? (Number(elem?.year_amount || 0) / 12) : null;
                            const priceToShow = isFreePlan ? elem?.month_amount : isYearlyView ? yearlyMonthlyPrice : elem?.month_amount;
                            const planInterval = isFreePlan ? "month" : planTab;
                            const displayInterval = isYearlyView ? "month" : planInterval;

                            return (
                                <div className={`planbox max-sm:mx-auto w-80 max-w-80 box border border-lightGray rounded-2xl p-5 relative hover:bg-gradient-to-br from-secondary to-primary group bg-white shadow  ${elem?.plan_type}`} key={elem?.id}>
                                    <div className={` `}>


                                        {elem?.most_popular && (
                                            <span className="absolute overflow-hidden left-4 -top-4 bg-quoteAvailable text-white font-semibold px-3 py-1 rounded-lg shadow-lg z-10 text-xs shimmer-badge">
                                                Most Popular
                                            </span>
                                        )}
                                        {elem?.trial_days > 0 && (
                                            <span className="absolute right-4 -top-4 bg-primary text-white rounded-tr-lg rounded-tl-lg px-1 pt-1 pb-5 z-10 flex flex-col items-center justify-center text-center leading-tight text-xs before:content-[''] before:absolute before:bottom-0 before:left-1/2 before:-translate-x-1/2 before:border-x-[16px] before:border-x-transparent before:border-b-[12px] before:border-b-white group-hover:before:border-b-[#c370ab]">
                                                <span className="2xl:text-2xl text-xl font-semibold">{elem?.trial_days}</span>
                                                <span>Days</span>
                                                Free<br /> Trial
                                            </span>
                                        )}

                                        <h5 className="2xl:text-2xl text-xl font-bold group-hover:text-white mb-2">{elem?.name} </h5>
                                        <span className="2xl:text-sm text-xs leading-tight block text-tertiary pr-10 min-h-9 group-hover:text-white/75">{elem?.description}</span>

                                        <div className={`2xl:text-4xl text-3xl group-hover:text-white leading-tight font-bold md:mb-6 mb-5 md:mt-4 mt-4`}>
                                            US${formatPrice(priceToShow, { forceTwoDecimals: isYearlyView })}
                                            <span className={`group-hover:text-white text-xl opacity-60 capitalize`}>/{displayInterval}</span>
                                        </div>
                                        {isYearlyView && (
                                            <span className="block text-xs text-gray group-hover:text-white/75 -mt-3 mb-4">
                                                Billed yearly at US${formatPrice(elem?.year_amount)}
                                            </span>
                                        )}


                                        {role == "brand" && (
                                            <span
                                                onClick={() => handlePlanButtonClick(elem)}
                                                className={`cursor-pointer rounded-md w-full py-3 font-medium text-center text-base flex items-center justify-center gap-1.5 ${elem?.plan_type === "premium" ? "border-t-0 border-b-0 border-transparent rounded-md font-medium focus-visible:outline-none bg-gradient-to-l from-secondary to-primary text-white group-hover:bg-black" : "bg-[#c3c3c3] text-black"} `}
                                            >
                                                {getButtonText(elem)}
                                                {/* {loadingPlanId === elem?.id && <LoaderSVG />} */}
                                            </span>
                                        )}
                                        <div className="list md:mt-8 mt-4">
                                            <span className="text-sm text-gray font-medium leading-6 group-hover:text-white/75 mb-4 block">{elem?.parent_plan_id ? `Everything in ${elem?.parent?.name}, plus` : "Includes"}</span>
                                            <ul className="list-none">
                                                {
                                                    elem?.permission?.map((data) => (
                                                        data?.is_enable && data?.description && <li key={data?.id} className={`relative plancontent mb-4 text-sm font-medium leading-6 group-hover:text-white ${data?.type == 'chat_with_influencers' ? "hidden" : ""}`}>{data?.description}
                                                        </li>
                                                    ))
                                                }
                                            </ul>
                                        </div>
                                        {role !== "brand" ? <ActivePlan elem={elem} refetch={refetch} /> : null}
                                        {role !== "brand" &&
                                            <Link href={`/admin/plan/edit-plan/${elem?.slug}`} className="flex items-center justify-center gap-2 text-primary font-medium text-base mt-2 group-hover:text-white underline">
                                                {/* <Image src={edit} alt='Logo' className="w-6" /> */}
                                                <span>Edit Plan</span>
                                            </Link>
                                        }
                                    </div>
                                </div>
                            )
                        })
                        :
                        "No Plans"
                }
            </div>
            {modal && <ActivePlanModal modal={modal} setModal={setModal} planRefetch={refetch} setCurrentPlan={setCurrentPlan} translations={translations} setPremiumModal={setPremiumModal} listRefetch={listRefetch} planTab={planTab} setMainModal={setMainModal} UserData={UserData} selfRefetch={selfRefetch} selfLoader={selfLoader} />}
            {freeModal && <ConfirmationModal loader={subscriptionLoader} modal={freeModal} args={{ message: "Are you sure you want to activate free plan?", title: "Activate Plan" }} setModal={setFreeModal} callbackFunction={callbackFunction} translations={translations} />}
        </>
    );
}

export default PlanListing;
