"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { motion } from "framer-motion";
import {
    Check,
    Shield,
    Star,
    ArrowRight,
} from "lucide-react";
import Header from "../components/Header";
import Footer from "../components/Footer";
import { useGetPlansQuery, useGetMyPlansQuery } from "@/redux/apis/planApi";
import { useInitiatePurchaseMutation, useVerifyPaymentMutation } from "@/redux/apis/paymentApi";
import { selectCurrentUser, selectIsAuthenticated } from "@/redux/slices/authSlice";

// Add global Razorpay type
declare global {
    interface Window {
        Razorpay: any;
    }
}

const PlanCard = ({ plan, index, handleBuyPlan, loadingPlanId, disabled, customButtonText }: {
    plan: any,
    index: number,
    handleBuyPlan: (plan: any) => void,
    loadingPlanId: number | null,
    disabled?: boolean,
    customButtonText?: string
}) => (
    <motion.div
        key={plan.id}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: index * 0.1 + 0.2 }}
        className="relative p-6 sm:p-8 rounded-2xl bg-white border border-gray-200 hover:border-blue-500 transition-all duration-300 group hover:shadow-xl hover:shadow-blue-500/5 flex flex-col h-full"
    >
        {/* Popular Badge */}
        {plan.name?.toLowerCase().includes("premium") && (
            <div className="absolute top-0 right-0 -mt-4 mr-4 px-4 py-1 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-xs font-bold rounded-full shadow-lg">
                POPULAR
            </div>
        )}

        <div className="mb-6 sm:mb-8">
            <h3 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-3 sm:mb-4">{plan.name}</h3>
            <div className="prose prose-sm text-gray-600 font-medium leading-relaxed whitespace-pre-line max-w-none line-clamp-4">
                {plan.description}
            </div>
        </div>

        <div className="mb-6 sm:mb-8 p-5 sm:p-6 bg-blue-50/50 rounded-2xl border border-blue-100/50">
            {(() => {
                const total = Number(plan.price);
                const basePrice = Math.round(total / 1.18);
                const gst = total - basePrice;
                return (
                    <div className="space-y-2 sm:space-y-3">
                        <div className="flex justify-between items-center text-gray-600 font-medium text-sm sm:text-base">
                            <span>Base Price:</span>
                            <span>{plan.currency} {basePrice.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
                        </div>
                        <div className="flex justify-between items-center text-gray-600 font-medium pb-3 border-b border-blue-100 italic text-sm sm:text-base">
                            <span>GST (18%):</span>
                            <span>{plan.currency} {gst.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
                        </div>
                        <div className="pt-1">
                            <div className="flex items-baseline gap-2">
                                <span className="text-2xl sm:text-4xl font-black text-blue-600">{plan.currency} {total.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
                                <span className="text-blue-500/80 font-semibold text-sm sm:text-base">/{plan.validity} days</span>
                            </div>
                            <p className="text-xs text-blue-500 font-bold mt-1 uppercase tracking-wider">Total Amount (Incl. GST)</p>
                        </div>
                    </div>
                );
            })()}
            {plan.originalPrice && Number(plan.originalPrice) > Number(plan.price) && (
                <p className="text-sm text-gray-400 line-through mt-4 font-medium italic">
                    Original Price: {plan.currency} {Number(plan.originalPrice).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                </p>
            )}
        </div>

        <div className="space-y-4 sm:space-y-5 mb-8 sm:mb-10 flex-grow">
            <div className="flex items-start gap-4 text-gray-700 bg-white/50 p-1 rounded-lg transition-colors hover:bg-blue-50/30">
                <div className="mt-1 p-1.5 rounded-full bg-blue-100 text-blue-600 flex-shrink-0">
                    <Check className="w-4 h-4" />
                </div>
                <div className="flex flex-col">
                    <span className="font-bold text-gray-900 text-sm sm:text-base">Coverage</span>
                    <span className="text-xs sm:text-sm text-gray-500 italic">{plan.planFor}</span>
                </div>
            </div>
            <div className="flex items-start gap-4 text-gray-700 bg-white/50 p-1 rounded-lg transition-colors hover:bg-blue-50/30">
                <div className="mt-1 p-1.5 rounded-full bg-blue-100 text-blue-600 flex-shrink-0">
                    <Shield className="w-4 h-4" />
                </div>
                <div className="flex flex-col">
                    <span className="font-bold text-gray-900 text-sm sm:text-base">Security</span>
                    <span className="text-xs sm:text-sm text-gray-500">Fast & Fully Secure Payments</span>
                </div>
            </div>
            <div className="flex items-start gap-4 text-gray-700 bg-white/50 p-1 rounded-lg transition-colors hover:bg-blue-50/30">
                <div className="mt-1 p-1.5 rounded-full bg-blue-100 text-blue-600 flex-shrink-0">
                    <Star className="w-4 h-4" />
                </div>
                <div className="flex flex-col">
                    <span className="font-bold text-gray-900 text-sm sm:text-base">Support</span>
                    <span className="text-xs sm:text-sm text-gray-500">24/7 Priority Assistance</span>
                </div>
            </div>
        </div>

        <button
            onClick={() => handleBuyPlan(plan)}
            disabled={loadingPlanId === plan.id || disabled}
            className={`w-full py-3 sm:py-4 rounded-xl font-semibold transition-all flex items-center justify-center gap-2 shadow-lg shadow-blue-500/20 mt-auto text-sm sm:text-base ${disabled
                ? "bg-gray-300 text-gray-500 cursor-not-allowed"
                : "bg-blue-600 text-white hover:bg-blue-700 group-hover:scale-[1.02] active:scale-[0.98]"
                }`}
        >
            {loadingPlanId === plan.id ? (
                <>
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Processing...
                </>
            ) : (
                <>
                    {customButtonText || "Get Started"}
                    {!disabled && <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />}
                </>
            )}
        </button>
    </motion.div>
);

export default function PlansPage() {
    const router = useRouter();
    const isAuthenticated = useSelector(selectIsAuthenticated);
    const user = useSelector(selectCurrentUser);
    const [loadingPlanId, setLoadingPlanId] = useState<number | null>(null);

    // Fetch plans
    const { data: plansData, isLoading: isLoadingPlans, error: plansError } = useGetPlansQuery({
        status: "active",
    });

    // Fetch user purchased plans
    const { data: myPlansData } = useGetMyPlansQuery(undefined, { skip: !isAuthenticated });

    // Check if user has basic membership (using dailyPostActive AND purchased plans list for robustness)
    const hasBasicMembership =
        (user as any)?.dailyPostActive === true ||
        myPlansData?.data?.some(p => {
            const name = p.plan?.name?.toLowerCase() || "";
            return (name.includes("membership") && name.includes("basic")) ||
                p.planId === 17 || p.plan?.id === 17 ||
                p.planId === 10 || p.plan?.id === 10;
        }) || false;

    const [initiatePurchase] = useInitiatePurchaseMutation();
    const [verifyPayment] = useVerifyPaymentMutation();

    const handleBuyPlan = async (plan: any) => {
        if (!isAuthenticated) {
            router.push("/login?redirect=/plans");
            return;
        }

        if (!window.Razorpay) {
            alert("Razorpay SDK not loaded. Please refresh the page.");
            return;
        }

        try {
            setLoadingPlanId(plan.id);

            // 1. Initiate Purchase
            const initiateResult = await initiatePurchase({ planId: plan.id }).unwrap();

            if (!initiateResult.success) {
                throw new Error(initiateResult.message);
            }

            const { orderId, amount, currency, keyId } = initiateResult.data;

            // 2. Open Razorpay Checkout
            const options = {
                key: keyId,
                amount: amount,
                currency: currency,
                name: "Tender Portal",
                description: `Subscription for ${plan.name}`,
                order_id: orderId,
                prefill: {
                    name: user?.name || "",
                    email: user?.email || "",
                    contact: user?.phone || "",
                },
                theme: {
                    color: "#3B82F6", // Primary blue color
                },
                handler: async function (response: any) {
                    try {
                        // 3. Verify Payment
                        const verifyResult = await verifyPayment({
                            razorpay_order_id: response.razorpay_order_id,
                            razorpay_payment_id: response.razorpay_payment_id,
                            razorpay_signature: response.razorpay_signature,
                            planId: plan.id,
                        }).unwrap();

                        if (verifyResult.success) {
                            alert("Payment Successful! Plan Activated.");
                            router.push("/profile");
                        } else {
                            alert("Payment Verification Failed: " + verifyResult.message);
                        }
                    } catch (verifyError: any) {
                        console.error("Payment verification failed:", verifyError);
                        alert("Payment verification failed: " + (verifyError.data?.message || verifyError.message));
                    } finally {
                        setLoadingPlanId(null);
                    }
                },
                modal: {
                    ondismiss: function () {
                        setLoadingPlanId(null);
                    },
                },
            };

            const rzp1 = new window.Razorpay(options);
            rzp1.on("payment.failed", function (response: any) {
                alert("Payment Failed: " + response.error.description);
                setLoadingPlanId(null);
            });
            rzp1.open();

        } catch (error: any) {
            console.error("Error initiating payment:", error);
            alert("Failed to initiate payment: " + (error.data?.message || error.message));
            setLoadingPlanId(null);
        }
    };

    const planOrder = [
        "basic",
        "silver",
        "gold",
        "premium",
        "classic",
        "corporate",
        "priority"
    ];

    const tenderPlans = (plansData?.data || [])
        .filter(p => {
            const categoryName = p.category?.name || p.categoryId?.name || "";
            return categoryName.toLowerCase().includes("tender");
        })
        .sort((a, b) => {
            const nameA = a.name.toLowerCase();
            const nameB = b.name.toLowerCase();

            const indexA = planOrder.findIndex(order => nameA.includes(order));
            const indexB = planOrder.findIndex(order => nameB.includes(order));

            if (indexA !== -1 && indexB !== -1) return indexA - indexB;
            if (indexA !== -1) return -1;
            if (indexB !== -1) return 1;
            return 0;
        });

    return (
        <div className="min-h-screen flex flex-col bg-gray-50 transition-colors duration-300">
            <Header />
            <main className="flex-1 pt-24 pb-16">
                <div className="w-full px-4 sm:px-6 lg:px-8 py-8">
                    <div className="max-w-7xl mx-auto">
                        {/* Header */}
                        <div className="text-center mb-16">
                            <motion.h1
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                className="text-4xl md:text-5xl font-bold text-gray-900 mb-4"
                            >
                                Choose Your Plan
                            </motion.h1>
                            <motion.p
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ delay: 0.1 }}
                                className="text-xl text-gray-600 max-w-2xl mx-auto"
                            >
                                Get access to premium tenders and exclusive business opportunities.
                            </motion.p>
                        </div>

                        {/* Plans Section */}
                        {isLoadingPlans ? (
                            <div className="flex justify-center items-center py-12">
                                <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
                            </div>
                        ) : plansError ? (
                            <div className="text-center text-red-500 py-12">
                                Failed to load plans. Please try again later.
                            </div>
                        ) : (
                            <div className="space-y-20">
                                {tenderPlans.length > 0 && (
                                    <div>
                                        <div className="flex items-center gap-4 mb-8">
                                            <h2 className="text-2xl font-bold text-gray-900 whitespace-nowrap">Tender Portal Plans</h2>
                                            <div className="h-px w-full bg-gradient-to-r from-blue-200 to-transparent"></div>
                                        </div>
                                        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
                                            {tenderPlans.map((plan: any, index: number) => {
                                                const pName = plan.name?.toLowerCase() || "";
                                                const isBasicPlan = (pName.includes("membership") && pName.includes("basic")) ||
                                                    plan.id === 17 || plan.id === 10;
                                                let isDisabled = false;
                                                let buttonText = "Get Started";

                                                if (isAuthenticated) {
                                                    if (!hasBasicMembership) {
                                                        // If basic not bought, only basic is enabled
                                                        if (!isBasicPlan) {
                                                            isDisabled = true;
                                                            buttonText = "Requires Basic Membership";
                                                        }
                                                    } else {
                                                        // If basic is bought, basic is disabled and others are enabled
                                                        if (isBasicPlan) {
                                                            isDisabled = true;
                                                            buttonText = "Active Plan";
                                                        } else {
                                                            // Check if this specific plan is already bought
                                                            const isAlreadyPurchased = myPlansData?.data?.some(p =>
                                                                p.planId === plan.id || p.plan?.id === plan.id
                                                            );
                                                            if (isAlreadyPurchased) {
                                                                isDisabled = true;
                                                                buttonText = "Active Plan";
                                                            }
                                                        }
                                                    }
                                                }

                                                return (
                                                    <PlanCard
                                                        key={plan.id}
                                                        plan={plan}
                                                        index={index}
                                                        handleBuyPlan={handleBuyPlan}
                                                        loadingPlanId={loadingPlanId}
                                                        disabled={isDisabled}
                                                        customButtonText={buttonText}
                                                    />
                                                );
                                            })}
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </main>
            <Footer />
        </div>
    );
}
