"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import { withCDN } from "@/src/lib/utils";
import { X, Tag, Check, AlertCircle, Sparkles, CreditCard, ChevronDown, CalendarDays } from "lucide-react";
import { initiatePaymentAction, setupPaymentAction } from "@/src/lib/actions/paymentAction";
import { formatPaymentErrorMessage } from "@/src/lib/utils/paymentErrorMessage";
import { verifyCouponAction } from "@/src/lib/actions/couponAction";
import { fetchPaymentPlansAction } from "@/src/lib/actions/paymentPlansAction";
import type { PaymentPlan } from "@/src/lib/services/classwiseClassesService";
import type { PaymentPayload, SetupPaymentPayload } from "@/src/lib/services/paymentService";
import { useBodyScrollLock } from "@/src/lib/hooks/useBodyScrollLock";
import { useSearchParams } from "next/navigation";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { getLocalizedUrl } from "@/src/lib/utils/urlHelper";

interface SubmissionModalProps {
  isOpen: boolean;
  submittedData: Array<Record<string, string>> | null;
  registrationId: string | null;
  selectedClass?: any;
  successMessage?: string;
  franchiseeAccountId?: string;
  onClose: () => void;
  onPayNow: () => void;
}

export default function SubmissionModal({
  isOpen,
  submittedData,
  registrationId,
  selectedClass,
  successMessage,
  franchiseeAccountId,
  onClose,
  onPayNow,
}: SubmissionModalProps) {
  const [isProcessing, setIsProcessing] = useState(false);
  // Handing off to checkout is a hard redirect, so language and tenant have to
  // be carried in the URL — the router isn't involved to do it for us.
  const { currentLanguage } = useLanguage();
  const franchiseeId = useSearchParams().get("franchiseeId");

  // Coupon states
  const [couponCode, setCouponCode] = useState("");
  const [isCouponApplied, setIsCouponApplied] = useState(false);
  const [isVerifyingCoupon, setIsVerifyingCoupon] = useState(false);
  const [couponData, setCouponData] = useState<{
    discount: number;
    discount_type: "percentage" | "fixed";
    coupon_code: string;
  } | null>(null);
  const [couponError, setCouponError] = useState("");
  const [showCouponInput, setShowCouponInput] = useState(false);
  const [paymentError, setPaymentError] = useState<string | null>(null);

  // Payment plans states
  const [showPaymentPlans, setShowPaymentPlans] = useState(false);
  const [paymentPlans, setPaymentPlans] = useState<PaymentPlan[]>([]);
  const [isLoadingPlans, setIsLoadingPlans] = useState(false);
  const [plansError, setPlansError] = useState("");

  console.log(selectedClass);

  // Extract email from submitted data
  const getEmailFromData = () => {
    if (!submittedData || submittedData.length === 0) return "";
    for (const step of submittedData) {
      if (step.email || step.Email) return step.email || step.Email;
    }
    return "";
  };

  // Get original price from selected class
  const getOriginalPrice = () => {
    if (selectedClass?.value) {
      return parseFloat(selectedClass.value);
    }
    return 25.0;
  };

  // Calculate discount amount
  const getDiscountAmount = () => {
    if (!isCouponApplied || !couponData) return 0;

    const originalPrice = getOriginalPrice();

    if (couponData.discount_type === "percentage") {
      return (originalPrice * couponData.discount) / 100;
    } else {
      return couponData.discount;
    }
  };

  // Get final price after discount
  const getFinalPrice = () => {
    const originalPrice = getOriginalPrice();
    const discount = getDiscountAmount();
    return Math.max(0, originalPrice - discount); // Ensure price doesn't go negative
  };

  // Get currency
  const getCurrency = () => {
    return "usd";
  };

  // Format price for display
  const formatPrice = (amount: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: getCurrency().toUpperCase(),
    }).format(amount);
  };

  // Get price details for display
  const getPriceDetails = () => {
    if (!selectedClass) return null;

    const feeBasis = selectedClass.fee_basis || "per_lesson";
    const numberOfLessons = selectedClass.number_of_lessons || 1;
    const frequency = selectedClass.frequency || "daily";

    let priceLabel = "";
    if (feeBasis === "per_lesson") {
      priceLabel = `Per Lesson`;
    } else if (feeBasis === "per_month") {
      priceLabel = `Per Month`;
    } else if (feeBasis === "one_time") {
      priceLabel = `One Time Payment`;
    } else {
      priceLabel = `Total`;
    }

    return {
      label: priceLabel,
      lessons: numberOfLessons,
      frequency: frequency,
      feeBasis: feeBasis,
    };
  };

  // Handle coupon verification
  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) {
      setCouponError("Please enter a coupon code");
      return;
    }

    if (!selectedClass?.id) {
      setCouponError("Class information not available");
      return;
    }

    setIsVerifyingCoupon(true);
    setCouponError("");

    try {
      const response = await verifyCouponAction(couponCode.trim(), selectedClass.id);

      if (response.success && response.data) {
        setCouponData(response.data);
        setIsCouponApplied(true);
        setCouponError("");
        console.log("[Coupon] Applied successfully:", response.data);
      } else {
        setCouponError(response.message || "Invalid coupon code");
        setIsCouponApplied(false);
        setCouponData(null);
      }
    } catch (error) {
      console.error("[Coupon] Verification error:", error);
      setCouponError("Failed to verify coupon. Please try again.");
      setIsCouponApplied(false);
      setCouponData(null);
    } finally {
      setIsVerifyingCoupon(false);
    }
  };

  // Remove coupon
  const handleRemoveCoupon = () => {
    setCouponCode("");
    setIsCouponApplied(false);
    setCouponData(null);
    setCouponError("");
  };

  // Fetch payment plans
  const handleTogglePaymentPlans = async () => {
    if (showPaymentPlans) {
      setShowPaymentPlans(false);
      return;
    }

    const groupId = selectedClass?.id;
    const accountId = franchiseeAccountId;

    if (!groupId || !accountId) {
      setPlansError("Class or account information not available.");
      setShowPaymentPlans(true);
      return;
    }

    setIsLoadingPlans(true);
    setPlansError("");
    setShowPaymentPlans(true);

    try {
      const response = await fetchPaymentPlansAction(groupId, accountId);

      if (response.success && response.data.length > 0) {
        setPaymentPlans(response.data.slice(0, 5));
      } else {
        setPlansError(response.message || "Failed to load payment plans.");
        setPaymentPlans([]);
      }
    } catch (err) {
      console.error("[PaymentPlans] action error:", err);
      setPlansError("Unable to load payment plans. Please try again.");
      setPaymentPlans([]);
    } finally {
      setIsLoadingPlans(false);
    }
  };

  // Format due date
  const formatDueDate = (dateStr: string) => {
    const d = new Date(dateStr);
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  };

  // Lock background scroll without jumping the page to the top.
  useBodyScrollLock(isOpen);

  useEffect(() => {
    if (isOpen) {
      setPaymentError(null);
    }
  }, [isOpen, submittedData, selectedClass]);

  const handlePayNow = async () => {
    setIsProcessing(true);
    setPaymentError(null);
    try {
      const email = getEmailFromData();
      let response;

      // Check if this is a demo class
      if (selectedClass?.is_demo) {
        // For demo classes, use setup payment endpoint
        if (!registrationId) {
          alert("Registration ID not available. Please try again.");
          setIsProcessing(false);
          return;
        }

        const setupPaymentPayload: SetupPaymentPayload = {
          user_id: 1,
          gateway: "stripe",
          email: email,
          registration_id: registrationId,
        };

        console.log("[SubmissionModal] Setup payment payload (demo class):", setupPaymentPayload);
        response = await setupPaymentAction(setupPaymentPayload);
      } else {
        // For paid classes, use regular payment endpoint
        const amount = getFinalPrice(); // Use final price after discount

        // Build payment payload with class details
        const paymentPayload: PaymentPayload = {
          user_id: 1,
          gateway: "stripe",
          amount: amount,
          currency: getCurrency(),
          email: email,
          registration_id: registrationId || undefined,
          // Include class details
          class_id: selectedClass?.id,
          class_name: selectedClass?.label,
          fee_basis: selectedClass?.fee_basis,
          number_of_lessons: selectedClass?.number_of_lessons,
          frequency: selectedClass?.frequency,
          // Include submitted form data
          submitted_data: submittedData || undefined,
        };

        console.log("[SubmissionModal] Payment payload:", paymentPayload);
        response = await initiatePaymentAction(paymentPayload);
      }

      if (response.status && response.data) {
        console.log("[SubmissionModal] Payment/Setup initiated successfully:", response);
        const paymentData = Array.isArray(response.data) ? response.data[0] : response.data;
        // ✅ Use registration_id from payment response (not payment record id)
        const responseRegistrationId = paymentData?.registration_id || registrationId;
        const clientSecret = paymentData?.response?.client_secret;
        const finalAmount = selectedClass?.is_demo ? 0 : getFinalPrice();

        if (responseRegistrationId && clientSecret) {
          const intentId =
            paymentData?.payment_intent_id ||
            paymentData?.response?.id ||
            clientSecret.split("_secret_")[0];
          // Save payment details using correct registration ID
          sessionStorage.setItem(`payment_${responseRegistrationId}`, clientSecret);
          const stripeAccountId =
            paymentData?.stripe_account_id ||
            paymentData?.response?.metadata?.stripe_account_id;
          if (stripeAccountId) {
            sessionStorage.setItem(
              `stripe_account_${responseRegistrationId}`,
              stripeAccountId
            );
          }
          if (intentId) {
            sessionStorage.setItem(`payment_intent_${responseRegistrationId}`, intentId);
          }
          sessionStorage.setItem(`amount_${responseRegistrationId}`, finalAmount.toString());
          sessionStorage.setItem(`submission_${responseRegistrationId}`, responseRegistrationId);
          // Save the registration ID for reference
          sessionStorage.setItem(`registration_id`, responseRegistrationId.toString());

          setTimeout(() => {
            window.location.href = getLocalizedUrl(
              `/pay/${responseRegistrationId}`,
              currentLanguage,
              franchiseeId,
            );
          }, 100);
        } else {
          alert("Payment configuration error. Please try again.");
          setIsProcessing(false);
        }
      } else {
        console.error("[SubmissionModal] Payment failed:", response.message);

        const userMessage = formatPaymentErrorMessage(response.message);
        if (userMessage.toLowerCase().includes("not configured their payment setup")) {
          setPaymentError(userMessage);
        } else {
          alert(userMessage || "Payment failed. Please try again.");
        }

        setIsProcessing(false);
      }
    } catch (error) {
      console.error("[SubmissionModal] Payment exception:", error);
      alert("An error occurred while processing payment. Please try again.");
      setIsProcessing(false);
    }
  };

  const priceDetails = getPriceDetails();

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/40 z-[99999]"
          />

          {/* Modal - Full page scrollable */}
          <motion.div
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 50 }}
            transition={{ type: "spring", damping: 25, stiffness: 300 }}
            className="fixed inset-0 z-[100000] overflow-y-scroll w-screen h-[100dvh]"
            style={{
              scrollbarWidth: "thin",
              scrollbarColor: "#0097DC #E8E8E8",
            }}
          >
            <style>{`
              ::-webkit-scrollbar {
                width: 8px;
              }
              ::-webkit-scrollbar-track {
                background: #E8E8E8;
              }
              ::-webkit-scrollbar-thumb {
                background: #0097DC;
                border-radius: 4px;
              }
              ::-webkit-scrollbar-thumb:hover {
                background: #0077B6;
              }
            `}</style>
            <div className="min-h-[100dvh] flex items-start justify-center px-4 py-4 pt-24">
              <div className="w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden mt-0">
                {/* Header with Close Button */}
                <div className="relative bg-gradient-to-r from-[#0097DC] to-[#0077B6] p-4 md:p-6">
                  <button
                    onClick={onClose}
                    className="absolute top-3 right-3 md:top-4 md:right-4 bg-white/20 hover:bg-white/30 rounded-full p-2 transition-colors cursor-pointer"
                  >
                    <X size={20} className="text-white" />
                  </button>

                  <div className="text-center text-white pr-8">
                    <h2 className="text-xl md:text-2xl font-bold font-[Signika] mb-1">
                      Registration Confirmed!
                    </h2>
                    <p className="text-xs md:text-sm opacity-90 font-[Signika]">
                      {successMessage || "Thank you for completing your registration"}
                    </p>
                  </div>
                </div>

                {/* Content */}
                <div className="p-4 md:p-6">
                  {/* Success Image */}
                  <div className="flex justify-center mb-6">
                    <motion.div
                      initial={{ scale: 0 }}
                      animate={{ scale: 1 }}
                      transition={{ delay: 0.2, type: "spring", damping: 20 }}
                      className="relative"
                    >
                      <Image
                        src={withCDN("/congratulations.png")}
                        alt="Congratulations"
                        width={180}
                        height={160}
                        className="rounded-2xl"
                      />
                    </motion.div>
                  </div>

                  {/* Submitted Data */}
                  {submittedData && submittedData.length > 0 && (
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.3 }}
                      className="bg-gradient-to-br from-[#F5F5F5] to-[#EFEFEF] rounded-2xl p-4 mb-6"
                    >
                      <h3 className="text-base md:text-lg font-bold text-[#58585A] mb-4 font-[Signika] text-center">
                        Your Registration Details
                      </h3>

                      <div className="space-y-3">
                        {submittedData.map((stepData, stepIndex) => (
                          <div
                            key={stepIndex}
                            className="bg-white rounded-xl p-3 shadow-sm hover:shadow-md transition-shadow"
                          >
                            {stepIndex < submittedData.length - 1 && (
                              <p className="text-xs text-[#0097DC] uppercase tracking-widest font-bold font-[Signika] mb-2">
                                Step {stepIndex + 1}
                              </p>
                            )}

                            <div className="space-y-1">
                              {Object.entries(stepData).map(([key, value]) => {
                                if (
                                  key.startsWith("step_") ||
                                  key.startsWith("agree_step_")
                                ) {
                                  return null;
                                }

                                return (
                                  <div
                                    key={key}
                                    className="flex justify-between items-start gap-2 pb-1 border-b border-[#F0F0F0] last:border-b-0"
                                  >
                                    <span className="text-xs text-[#828282] font-[Signika] font-medium flex-shrink-0">
                                      {key
                                        .replace(/_/g, " ")
                                        .replace(/([A-Z])/g, " $1")
                                        .replace(/\b\w/g, (c) => c.toUpperCase())
                                        .trim()}:
                                    </span>

                                    <span className="text-xs font-bold text-[#58585A] font-[Signika] text-right flex-shrink-0">
                                      {String(value)}
                                    </span>
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        ))}
                      </div>
                    </motion.div>
                  )}

                  {/* Payment Section with Coupon */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4 }}
                    className="bg-gradient-to-br from-[#F0F8FF] to-[#E0F4FF] rounded-2xl p-4 mb-4"
                  >
                    {/* Price Display */}
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex-1">
                        <p className="text-xs text-[#828282] font-[Signika] mb-1">
                          {priceDetails?.label || "Total Amount Due"}
                        </p>

                        {/* Show original price with strikethrough if coupon applied */}
                        {isCouponApplied && (
                          <p className="text-sm text-[#828282] font-[Signika] line-through">
                            {formatPrice(getOriginalPrice())}
                          </p>
                        )}

                        <p className="text-2xl md:text-3xl font-bold text-[#0097DC] font-[Signika]">
                          {formatPrice(getFinalPrice())}
                        </p>

                        {priceDetails && priceDetails.feeBasis === "per_lesson" && (
                          <p className="text-xs text-[#828282] font-[Signika] mt-1">
                            {priceDetails.lessons} lessons • {priceDetails.frequency}
                          </p>
                        )}
                      </div>
                      <div className="text-4xl">💳</div>
                    </div>

                    {/* Discount Badge */}
                    {isCouponApplied && couponData && (
                      <motion.div
                        initial={{ scale: 0.8, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="flex items-center gap-2 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-3 mb-4"
                      >
                        <div className="bg-green-500 rounded-full p-1.5">
                          <Check size={14} className="text-white" />
                        </div>
                        <div className="flex-1">
                          <p className="text-xs font-bold text-green-700 font-[Signika]">
                            Coupon Applied: {couponData.coupon_code}
                          </p>
                          <p className="text-xs text-green-600 font-[Signika]">
                            You saved {formatPrice(getDiscountAmount())}
                            {couponData.discount_type === "percentage" && ` (${couponData.discount}% off)`}
                          </p>
                        </div>
                        <button
                          onClick={handleRemoveCoupon}
                          className="text-green-600 hover:text-green-700 cursor-pointer"
                        >
                          <X size={18} />
                        </button>
                      </motion.div>
                    )}

                    {/* Payment Plans + Coupon Section */}
                    {!isCouponApplied && !selectedClass?.is_demo && (
                      <div className="border-t border-[#D0E8F5] pt-4 space-y-3">

                        {/* Payment Plans Toggle */}
                        <button
                          onClick={handleTogglePaymentPlans}
                          className="flex items-center gap-2 text-[#0097DC] hover:text-[#0077B6] font-[Signika] text-sm font-semibold transition-colors cursor-pointer w-full"
                        >
                          <CreditCard size={16} />
                          View Payment Plans
                          <ChevronDown
                            size={14}
                            className={`ml-auto transition-transform duration-200 ${showPaymentPlans ? "rotate-180" : ""}`}
                          />
                        </button>

                        {/* Payment Plans Panel */}
                        {showPaymentPlans && (
                          <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: "auto", opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            className="overflow-hidden"
                          >
                            {isLoadingPlans ? (
                              <div className="flex items-center justify-center py-4 gap-2 text-[#0097DC]">
                                <div className="w-4 h-4 border-2 border-[#0097DC] border-t-transparent rounded-full animate-spin" />
                                <span className="text-xs font-[Signika]">
                                  Loading plans...
                                </span>
                              </div>
                            ) : plansError ? (
                              <div className="flex items-center gap-2 text-red-600 text-xs font-[Signika] bg-red-50 border border-red-200 rounded-lg p-2">
                                <AlertCircle size={14} />
                                {plansError}
                              </div>
                            ) : paymentPlans.length === 0 ? (
                              <div className="text-xs font-[Signika] text-[#828282] text-center py-2">
                                No payment plans available for this class.
                              </div>
                            ) : (
                              <div className="space-y-2">
                                <p className="text-xs font-[Signika] text-[#58585A] font-semibold mb-1">
                                  Upcoming Payment Plans
                                </p>
                                {paymentPlans.map((plan, idx) => (
                                  <div
                                    key={plan.id}
                                    className="flex items-center justify-between gap-3 bg-white border border-[#D0E8F5] rounded-xl px-3 py-2.5 shadow-sm"
                                  >
                                    <div className="flex items-center gap-2">
                                      <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white ${
                                        plan.status === "paid" ? "bg-green-500" : "bg-[#0097DC]"
                                      }`}>
                                        {idx + 1}
                                      </div>
                                      <div>
                                        <div className="flex items-center gap-1">
                                          <CalendarDays size={11} className="text-[#828282]" />
                                          <span className="text-xs font-[Signika] text-[#828282]">
                                            Due: {formatDueDate(plan.due_date)}
                                          </span>
                                        </div>
                                        <span className={`text-[10px] font-[Signika] capitalize font-semibold ${
                                          plan.status === "paid" ? "text-green-600" : "text-amber-600"
                                        }`}>
                                          {plan.status.replace(/_/g, " ")}
                                        </span>
                                      </div>
                                    </div>
                                    <span className="text-sm font-bold text-[#0097DC] font-[Signika]">
                                      ${parseFloat(plan.amount).toFixed(2)}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            )}
                          </motion.div>
                        )}

                        <div className="border-t border-[#D0E8F5] pt-3">
                        {!showCouponInput ? (
                          <button
                            onClick={() => setShowCouponInput(true)}
                            className="flex items-center gap-2 text-[#0097DC] hover:text-[#0077B6] font-[Signika] text-sm font-semibold transition-colors cursor-pointer"
                          >
                            <Tag size={16} />
                            Have a coupon code?
                            <Sparkles size={14} className="animate-pulse" />
                          </button>
                        ) : (
                          <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: "auto", opacity: 1 }}
                            className="space-y-2"
                          >
                            <label className="flex items-center gap-2 text-xs font-semibold text-[#58585A] font-[Signika] mb-2">
                              <Tag size={14} />
                              Enter Coupon Code
                            </label>

                            <div className="flex gap-2">
                              <div className="flex-1 relative">
                                <input
                                  type="text"
                                  value={couponCode}
                                  onChange={(e) => {
                                    setCouponCode(e.target.value.toUpperCase());
                                    setCouponError("");
                                  }}
                                  onKeyPress={(e) => {
                                    if (e.key === "Enter") {
                                      handleApplyCoupon();
                                    }
                                  }}
                                  placeholder="ENTER CODE"
                                  disabled={isVerifyingCoupon}
                                  className="w-full px-4 py-2.5 border-2 border-[#D0E8F5] rounded-xl font-[Signika] text-sm font-bold text-[#58585A] placeholder:text-[#BDBDBD] focus:outline-none focus:border-[#0097DC] disabled:opacity-50 disabled:cursor-not-allowed uppercase"
                                />
                              </div>

                              <button
                                onClick={handleApplyCoupon}
                                disabled={isVerifyingCoupon || !couponCode.trim()}
                                className="px-6 py-2.5 bg-gradient-to-r from-[#0097DC] to-[#0077B6] hover:from-[#0077B6] hover:to-[#005A8F] text-white rounded-xl font-[Signika] text-sm font-bold transition-all disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer whitespace-nowrap"
                              >
                                {isVerifyingCoupon ? "Verifying..." : "Apply"}
                              </button>
                            </div>

                            {couponError && (
                              <motion.div
                                initial={{ opacity: 0, y: -10 }}
                                animate={{ opacity: 1, y: 0 }}
                                className="flex items-center gap-2 text-red-600 text-xs font-[Signika] bg-red-50 border border-red-200 rounded-lg p-2"
                              >
                                <AlertCircle size={14} />
                                {couponError}
                              </motion.div>
                            )}

                            <button
                              onClick={() => {
                                setShowCouponInput(false);
                                setCouponCode("");
                                setCouponError("");
                              }}
                              className="text-[#828282] hover:text-[#58585A] text-xs font-[Signika] underline cursor-pointer"
                            >
                              Cancel
                            </button>
                          </motion.div>
                        )}
                        </div>
                      </div>
                    )}

                    {/* Demo Class Badge */}
                    {selectedClass?.is_demo && (
                      <motion.div
                        initial={{ scale: 0.8, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="flex items-center gap-2 bg-gradient-to-r from-amber-50 to-yellow-50 border-2 border-amber-200 rounded-xl p-4 mt-4"
                      >
                        <div className="bg-amber-500 rounded-full p-2">
                          <Sparkles size={18} className="text-white" />
                        </div>
                        <div className="flex-1">
                        <p className="text-sm font-bold text-amber-800 font-[Signika]">
  🎉 This is a Demo Class
</p>
<p className="text-xs text-amber-700 font-[Signika] mt-1">
  You're enrolled in a demo class. You can add a payment method now or skip this step.
</p>
                        </div>
                      </motion.div>
                    )}
                  </motion.div>

                  {/* Payment Error Message */}
                  <AnimatePresence>
                    {paymentError && (
                      <motion.div
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: "auto" }}
                        exit={{ opacity: 0, height: 0 }}
                        className="mb-6 px-4 py-3 bg-red-50 border-2 border-red-100 rounded-2xl flex items-start gap-3 shadow-sm"
                      >
                        <div className="bg-red-500 rounded-full p-1.5 flex-shrink-0 mt-0.5">
                          <AlertCircle size={14} className="text-white" />
                        </div>
                        <div className="flex-1">
                          <p className="text-sm font-bold text-red-800 font-[Signika]">
                            Payment Currently Unavailable
                          </p>
                          <p className="text-xs text-red-700 font-[Signika] mt-0.5 leading-relaxed">
                            {paymentError}
                          </p>
                        </div>
                        <button
                          onClick={() => setPaymentError(null)}
                          className="text-red-400 hover:text-red-600 transition-colors p-1 rounded-full hover:bg-red-100"
                        >
                          <X size={16} />
                        </button>
                      </motion.div>
                    )}
                  </AnimatePresence>

                  {/* Action Buttons */}
                  <div className="flex flex-col gap-2 mb-4 lg:flex-row-reverse lg:justify-center max-[767px]:items-center">
                    <motion.button
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.5 }}
                      onClick={handlePayNow}
                      disabled={isProcessing}
                      className="w-full lg:w-[250px] p-[10px] bg-gradient-to-r from-[#0097DC] to-[#0077B6] hover:from-[#0077B6] hover:to-[#005A8F] text-white font-bold font-[Signika] text-sm md:text-base rounded-full transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg hover:shadow-xl cursor-pointer"
                    >
                      {isProcessing
                        ? "Processing..."
                        : selectedClass?.is_demo
                          ? "Add Payment Method"
                          : "Proceed to Payment"}
                    </motion.button>

                    <motion.button
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.55 }}
                      onClick={onClose}
                      className="w-full lg:w-[120px] p-[10px] bg-[#E8E8E8] hover:bg-[#D8D8D8] text-[#58585A] font-bold font-[Signika] text-sm md:text-base rounded-full transition-all duration-200 cursor-pointer"
                    >
                      Close
                    </motion.button>
                  </div>

                  {/* Footer Message */}
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.6 }}
                    className="pt-3 border-t border-[#E0E0E0] text-center"
                  >
                    <p className="text-xs text-[#828282] font-[Signika]">
                      A confirmation email has been sent to your registered email address.
                    </p>
                    <p className="text-xs text-[#BDBDBD] font-[Signika] mt-1">
                      Thank you for choosing Young Engineers!
                    </p>
                  </motion.div>
                </div>
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
