"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import toast from "react-hot-toast";
import {
  useSubscriptionControllerCreateCheckoutV1,
  useSubscriptionControllerGetBillingHistoryV1,
  useSubscriptionControllerGetPlansV1,
  useSubscriptionControllerGetBillingPortalV1,
  useSubscriptionControllerGetSubscriptionStatusV1,
} from "@/api/user/practitioner-subscription/practitioner-subscription";
import { getUserDataCookie, setUserDataCookie, type UserData } from "@/lib/cookies";

// Fallback ES translations for plan feature strings not yet translated by the backend.
// Only used when the API does not return `monthly_es` / `yearly_es` for a plan.
const FEATURE_ES: Record<string, string> = {
  "Up to 10 practitioners": "Hasta 10 terapeutas",
  "Up to 5 practitioners": "Hasta 5 terapeutas",
  "Up to 20 practitioners": "Hasta 20 terapeutas",
  "Up to 50 practitioners": "Hasta 50 terapeutas",
  "Unlimited practitioners": "Terapeutas ilimitados",
  "Unlimited client screenings": "Evaluaciones de clientes ilimitadas",
  "Unlimited screenings": "Evaluaciones ilimitadas",
  "Dedicated account manager": "Gerente de cuenta dedicado",
  "Custom data retention policies": "Políticas de retención de datos personalizadas",
  "Advanced security features": "Funciones de seguridad avanzadas",
  "On-premise deployment option": "Opción de implementación en sus instalaciones",
  "24/7 phone support": "Soporte telefónico 24/7",
  "Custom training & onboarding": "Capacitación e incorporación personalizada",
  "Priority support": "Soporte prioritario",
  "Advanced analytics": "Análisis avanzado",
  "Team collaboration": "Colaboración en equipo",
  "All monthly features included": "Todas las funciones mensuales incluidas",
  "2 months free": "2 meses gratis",
};
const applyFeatureTranslations = (features: string[], locale: string): string[] =>
  locale === "es" ? features.map((f) => FEATURE_ES[f] ?? f) : features;

function PracticeManagerSubscriptionContent() {
  const t = useTranslations();
  const locale = useLocale();
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const [currentPage, setCurrentPage] = useState(1);
  const [pmBillingCycle, setPmBillingCycle] = useState<'monthly' | 'annual'>('annual');
  const [pendingCard, setPendingCard] = useState<string | null>(null);

  // Read user data from cookie
  const [userData, setUserData] = useState<UserData | null>(null);
  useEffect(() => {
    setUserData(getUserDataCookie());
  }, []);

  // Handle Stripe cancel redirect — show toast once then strip the query param
  useEffect(() => {
    if (searchParams.get("canceled") === "true") {
      toast.error(t("practiceManager.subscription.paymentCanceled"), { duration: 4000 });
      router.replace(pathname, { scroll: false });
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // --- API Hooks ---

  // Fetch subscription status — poll every 4s when incomplete so banner clears after Stripe webhook fires
  const { data: statusData, isLoading: isLoadingStatus, refetch: refetchStatus } = useSubscriptionControllerGetSubscriptionStatusV1(
    { query: { refetchInterval: (query) => (query.state.data?.data?.status === "incomplete" ? 4000 : false) } }
  );
  const subscriptionStatus = statusData?.data?.status || null;
  const periodEnd = statusData?.data?.current_period_end || null;
  const activePlanType = statusData?.data?.plan_type || null;

  // When returning from Stripe after successful payment, refetch immediately and show toast
  useEffect(() => {
    if (searchParams.get("success") === "true") {
      toast.success(t("practiceManager.subscription.paymentReceived"), { duration: 5000 });
      refetchStatus();
    }
  }, [searchParams]); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-sync toggle to match active plan type so the active card is highlighted correctly
  useEffect(() => {
    if (activePlanType === 'monthly' || activePlanType === 'annual') {
      setPmBillingCycle(activePlanType);
    }
  }, [activePlanType]);

  // Fetch plans from API
  const { data: plansData, isLoading: isLoadingPlans, error: plansError, refetch: refetchPlans } = useSubscriptionControllerGetPlansV1();

  // Separate individual and group plans
  const allPlans = plansData?.data || [];
  const groupRawPlan = allPlans.find((p) => ((p as any).subscription_type || 'individual') === 'group');
  const individualRawPlans = allPlans.filter((p) => ((p as any).subscription_type || 'individual') !== 'group');

  const individualPlans: Array<{ name: string; price: string; period: string; description: string; features: string[]; buttonText: string; buttonStyle: string; planType: "monthly" | "annual"; savings?: number }> = [];
  individualRawPlans.forEach((plan) => {
    const featuresObj = plan.features as Record<string, string[]> | undefined;
    const planName = locale === 'es' ? ((plan as any).name_es || plan.name) : plan.name;
    const planDescription = locale === 'es' ? ((plan as any).description_es || plan.description) : plan.description;
    const yearlySavings = plan.price_monthly && plan.price_yearly
      ? plan.price_monthly * 12 - plan.price_yearly
      : 0;
    if (plan.price_monthly) {
      const monthlyFeatures = applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.monthly_es || featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || []), locale);
      individualPlans.push({
        name: planName,
        price: `$${plan.price_monthly}`,
        period: t("practiceManager.subscription.perMonth"),
        description: planDescription,
        features: monthlyFeatures,
        buttonText: t("practiceManager.subscription.subscribeNow"),
        buttonStyle: "filled",
        planType: "monthly",
      });
    }
    if (plan.price_yearly) {
      const yearlyFeatures = applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.yearly_es || featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || []), locale);
      individualPlans.push({
        name: planName,
        price: `$${plan.price_yearly}`,
        period: t("practiceManager.subscription.perYear"),
        description: planDescription,
        features: yearlyFeatures,
        buttonText: t("practiceManager.subscription.upgradeNow"),
        buttonStyle: "outline",
        planType: "annual",
        savings: yearlySavings > 0 ? yearlySavings : undefined,
      });
    }
  });

  // Group/PM plan — single card with monthly/yearly toggle
  const groupPlanData = groupRawPlan ? (() => {
    const featuresObj = groupRawPlan.features as Record<string, string[]> | undefined;
    const groupSavings = groupRawPlan.price_monthly && groupRawPlan.price_yearly
      ? groupRawPlan.price_monthly * 12 - groupRawPlan.price_yearly
      : 0;
    return {
      name: locale === 'es' ? ((groupRawPlan as any).name_es || groupRawPlan.name) : groupRawPlan.name,
      description: locale === 'es' ? ((groupRawPlan as any).description_es || groupRawPlan.description) : groupRawPlan.description,
      priceMonthly: groupRawPlan.price_monthly ? `$${groupRawPlan.price_monthly}` : null,
      priceYearly: groupRawPlan.price_yearly ? `$${groupRawPlan.price_yearly}` : null,
      yearlySavings: groupSavings > 0 ? groupSavings : 0,
      featuresMonthly: applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.monthly_es || featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || []), locale),
      featuresYearly: applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.yearly_es || featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || []), locale),
    };
  })() : null;

  // Fetch billing history
  const { data: billingData, isLoading: isLoadingBilling, error: billingError } = useSubscriptionControllerGetBillingHistoryV1();
  const billingRecords = billingData?.data || [];
  const billingMeta = billingData?.meta;
  const totalPages = billingMeta?.totalPages || 1;

  useEffect(() => {
    if (billingError) {
      toast.error(t("practiceManager.subscription.billingLoadError"), { id: "billing-error", duration: 5000 });
    }
  }, [billingError]);

  const hasBillingHistory = !isLoadingBilling && billingRecords.length > 0;

  // Unified loading state - wait for all critical APIs to complete
  const isLoadingSubscriptionData = isLoadingPlans || isLoadingBilling || isLoadingStatus;

  // Status-aware subscription check
  const hasActiveSubscription = subscriptionStatus === "active" || subscriptionStatus === "past_due" || subscriptionStatus === "incomplete" || subscriptionStatus === "paused";

  // Show the current plan card for both active subscriptions and cancelled ones (user still has access until period end)
  const showSubscriptionCard = hasActiveSubscription || subscriptionStatus === "cancelled";

  const shouldDisableSubscribe = subscriptionStatus === "active" || subscriptionStatus === "past_due" || subscriptionStatus === "paused" || subscriptionStatus === "incomplete";

  const getStatusConfig = (status: string | null) => {
    switch (status) {
      case "active":
        return { label: t("practiceManager.subscription.activePlan"), bg: "bg-green-100", text: "text-green-600", dot: "bg-green-500" };
      case "past_due":
        return { label: t("practiceManager.subscription.pastDue"), bg: "bg-red-100", text: "text-red-600", dot: "bg-red-500" };
      case "incomplete":
        return { label: t("practiceManager.subscription.incomplete"), bg: "bg-yellow-100", text: "text-yellow-600", dot: "bg-yellow-500" };
      case "paused":
        return { label: t("practiceManager.subscription.paused"), bg: "bg-gray-100", text: "text-gray-600", dot: "bg-gray-500" };
      case "cancelled":
        return { label: t("practiceManager.subscription.cancelled"), bg: "bg-red-100", text: "text-red-600", dot: "bg-red-500" };
      default:
        return { label: t("practiceManager.subscription.activePlan"), bg: "bg-green-100", text: "text-green-600", dot: "bg-green-500" };
    }
  };

  // Stripe billing portal
  const portalMutation = useSubscriptionControllerGetBillingPortalV1({
    mutation: {
      onSuccess: (data: any) => {
        const portalUrl = data?.data?.portal_url || data?.portal_url;
        if (portalUrl) {
          window.open(portalUrl, '_blank');
        }
      },
      onError: () => {
        toast.error(t("practiceManager.subscription.portalError"));
      },
      onSettled: () => setPendingCard(null),
    },
  });

  const handlePortal = (cardId: string) => {
    setPendingCard(cardId);
    portalMutation.mutate();
  };

  // Stripe checkout mutation
  const checkoutMutation = useSubscriptionControllerCreateCheckoutV1({
    mutation: {
      onSuccess: (data: any) => {
        const checkoutUrl = data?.data?.checkout_url || data?.checkout_url;
        if (checkoutUrl) {
          window.location.href = checkoutUrl;
        } else if (data?.data?.subscription) {
          // SKIP_PAYMENT dev mode
          const current = getUserDataCookie();
          const devSubType = data?.data?.subscription?.subscription_type || current?.subscription_type || 'group';
          if (current) {
            setUserDataCookie({ ...current, has_active_subscription: true, subscription_type: devSubType });
          }
          toast.success(data?.data?.message || t("practiceManager.subscription.subscriptionActivated"));
          const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
          window.location.href = `${basePath}/practice-manager/dashboard`;
        } else {
          toast.error(t("practiceManager.subscription.checkoutError"));
        }
      },
      onError: (error: any) => {
        if (error?.response?.status === 400) {
          const message = error?.response?.data?.message || "";
          const isAlreadySubscribed = message.toLowerCase().includes("active subscription") || message.toLowerCase().includes("already");
          if (isAlreadySubscribed) {
            const currentUserData = getUserDataCookie();
            if (currentUserData) {
              setUserDataCookie({ ...currentUserData, has_active_subscription: true });
            }
            toast.dismiss();
            toast.success(message || t("practiceManager.subscription.alreadySubscribed"), { duration: 3000 });
            window.location.reload();
          } else {
            toast.error(message || t("practiceManager.subscription.checkoutFailed"), { duration: 5000 });
          }
        } else {
          toast.error(error?.response?.data?.message || t("practiceManager.subscription.checkoutFailedRetry"), { duration: 4000 });
        }
      },
    },
  });

  const handleSubscribe = (planType: 'monthly' | 'annual', subscriptionType: 'individual' | 'group' = 'group', cardId?: string) => {
    if (cardId) setPendingCard(cardId);
    checkoutMutation.mutate({ data: { plan_type: planType, subscription_type: subscriptionType } }, {
      onSettled: () => setPendingCard(null),
    });
  };

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const total = totalPages || 1;
    if (total <= 7) {
      for (let i = 1; i <= total; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, "...", total - 1, total);
      } else if (currentPage >= total - 2) {
        pages.push(1, 2, "...", total - 2, total - 1, total);
      } else {
        pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", total);
      }
    }
    return pages;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" });
  };

  const getStatusBadge = (status: string) => {
    const isSuccess = status?.toLowerCase() === "paid" || status?.toLowerCase() === "succeeded";
    const isPending = status?.toLowerCase() === "pending" || status?.toLowerCase() === "open";
    if (isSuccess) {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-50 text-green-600">
          <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
          {t("practiceManager.subscription.paid")}
        </span>
      );
    }
    if (isPending) {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-yellow-50 text-yellow-600">
          <span className="w-1.5 h-1.5 rounded-full bg-yellow-500" />
          {t("practiceManager.subscription.pending")}
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-red-50 text-red-600">
        <span className="w-1.5 h-1.5 rounded-full bg-red-500" />
        {t("practiceManager.subscription.failed")}
      </span>
    );
  };

  const CheckIcon = () => (
    <svg className="w-4 h-4 text-[#3B9EC9] mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
    </svg>
  );

  return (
    <>
      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 pt-24">
        {/* Unified Loading State */}
        {isLoadingSubscriptionData && (
          <div className="flex items-center justify-center py-16">
            <div className="flex flex-col items-center gap-3">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#3B9EC9]"></div>
              <p className="text-sm text-gray-500">{t("practiceManager.subscription.loadingInfo")}</p>
            </div>
          </div>
        )}

        {/* Content - only show when all data is loaded */}
        {!isLoadingSubscriptionData && (
        <>

        {/* ── FIRST-TIME USER: Welcome banner ── */}
        {subscriptionStatus === "none" && (
          <div className="bg-gradient-to-r from-[#3B9EC9]/10 to-[#3B9EC9]/5 border border-[#3B9EC9]/20 rounded-2xl p-6 mb-8 flex items-start gap-4">
            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-[#3B9EC9]/15 flex items-center justify-center">
              <svg className="w-5 h-5 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z" />
              </svg>
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900">{t("practiceManager.subscription.welcomeBannerTitle")}</h2>
              <p className="text-sm text-gray-600 mt-0.5">{t("practiceManager.subscription.welcomeBannerMessage")}</p>
            </div>
          </div>
        )}

        {/* Current Plan Card - shown for active subscriptions and cancelled ones (user still has access until period end) */}
        {showSubscriptionCard && (() => {
          const statusConfig = getStatusConfig(subscriptionStatus);
          return (
            <div className="mb-8 bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
                <div>
                  <h1 className="text-xl font-semibold text-gray-900">
                    {activePlanType === "monthly" ? t("practiceManager.subscription.monthlyPlan") : activePlanType === "annual" ? t("practiceManager.subscription.annualPlan") : t("practiceManager.subscription.currentPlan")}
                  </h1>
                  <p className="text-sm text-gray-500 mt-1">
                    {billingRecords.length > 0 ? `$${billingRecords[0].amount}` : ""}
                  </p>
                </div>
                <div className="flex flex-col items-start sm:items-end gap-2">
                  <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium ${statusConfig.bg} ${statusConfig.text}`}>
                    <span className={`w-1.5 h-1.5 rounded-full ${statusConfig.dot}`} />
                    {statusConfig.label}
                  </span>
                  <p className="text-sm text-[#3B9EC9]">
                    {subscriptionStatus === "cancelled"
                      ? t("practiceManager.subscription.accessUntil")
                      : t("practiceManager.subscription.nextBilling")}: {periodEnd ? new Date(periodEnd).toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" }) : "-"}
                  </p>
                  <button
                    onClick={() => portalMutation.mutate()}
                    disabled={portalMutation.isPending}
                    className="mt-1 flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#3B9EC9] bg-white border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {portalMutation.isPending ? (
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-[#3B9EC9]"></div>
                    ) : (
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M10.343 3.94c.09-.542.56-.94 1.11-.94h1.093c.55 0 1.02.398 1.11.94l.149.894c.07.424.384.764.78.93.398.164.855.142 1.205-.108l.737-.527a1.125 1.125 0 011.45.12l.773.774c.39.389.44 1.002.12 1.45l-.527.737c-.25.35-.272.806-.107 1.204.165.397.505.71.93.78l.893.15c.543.09.94.56.94 1.109v1.094c0 .55-.397 1.02-.94 1.11l-.893.149c-.425.07-.765.383-.93.78-.165.398-.143.854.107 1.204l.527.738c.32.447.269 1.06-.12 1.45l-.774.773a1.125 1.125 0 01-1.449.12l-.738-.527c-.35-.25-.806-.272-1.204-.107-.397.165-.71.505-.78.929l-.15.894c-.09.542-.56.94-1.11.94h-1.094c-.55 0-1.019-.398-1.11-.94l-.148-.894c-.071-.424-.384-.764-.781-.93-.398-.164-.854-.142-1.204.108l-.738.527c-.447.32-1.06.269-1.45-.12l-.773-.774a1.125 1.125 0 01-.12-1.45l.527-.737c.25-.35.273-.806.108-1.204-.165-.397-.506-.71-.93-.78l-.894-.15c-.542-.09-.94-.56-.94-1.109v-1.094c0-.55.398-1.02.94-1.11l.894-.149c.424-.07.765-.383.93-.78.165-.398.143-.854-.107-1.204l-.527-.738a1.125 1.125 0 01.12-1.45l.773-.773a1.125 1.125 0 011.45-.12l.737.527c.35.25.807.272 1.204.107.397-.165.71-.505.78-.929l.15-.894z" />
                        <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      </svg>
                    )}
                    {t("practiceManager.subscription.manageSubscription")}
                  </button>
                </div>
              </div>

              {/* Status-specific alert banners */}
              {subscriptionStatus === "past_due" && (
                <div className="mt-4 p-4 rounded-xl bg-red-50 border border-red-200 flex items-start gap-3">
                  <svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-red-700">{t("practiceManager.subscription.pastDueMessage")}</p>
                    <button
                      onClick={() => portalMutation.mutate()}
                      className="mt-2 text-sm font-medium text-red-600 underline hover:text-red-800 cursor-pointer"
                    >
                      {t("practiceManager.subscription.updatePayment")}
                    </button>
                  </div>
                </div>
              )}

              {subscriptionStatus === "incomplete" && (
                <div className="mt-4 p-4 rounded-xl bg-yellow-50 border border-yellow-200 flex items-start gap-3">
                  <svg className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-yellow-700">{t("practiceManager.subscription.incompleteMessage")}</p>
                    <button
                      onClick={() => {
                        const currentData = getUserDataCookie();
                        if (currentData) setUserDataCookie({ ...currentData, subscription_type: 'group' });
                        handleSubscribe((activePlanType as 'monthly' | 'annual') || 'monthly', 'group', 'complete-payment');
                      }}
                      disabled={!!pendingCard}
                      className="mt-2 inline-flex items-center gap-1.5 text-sm font-medium text-yellow-700 underline hover:text-yellow-900 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {pendingCard === 'complete-payment' ? (
                        <>
                          <div className="animate-spin rounded-full h-3.5 w-3.5 border-b-2 border-yellow-700"></div>
                          {t("practiceManager.subscription.processing")}
                        </>
                      ) : (
                        <>
                          {t("practiceManager.subscription.completePayment")}
                          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                          </svg>
                        </>
                      )}
                    </button>
                  </div>
                </div>
              )}
            </div>
          );
        })()}

        {/* Billing History */}
        {(hasActiveSubscription || hasBillingHistory) && (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 mb-12">
            <h2 className="text-lg font-semibold text-gray-900 mb-6">{t("practiceManager.subscription.billingHistory")}</h2>

            <div className="border border-gray-300 rounded-xl overflow-hidden">
              <div className="overflow-x-auto">
              <table className="w-full min-w-[550px]">
                <thead>
                  <tr className="bg-white border-b border-gray-300">
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600">{t("practiceManager.subscription.no")}</th>
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("practiceManager.subscription.date")}</th>
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("practiceManager.subscription.plan")}</th>
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("practiceManager.subscription.amount")}</th>
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("practiceManager.subscription.status")}</th>
                    <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("practiceManager.subscription.action")}</th>
                  </tr>
                </thead>
                <tbody>
                  {billingRecords.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="py-8 text-center text-gray-500">
                        {t("practiceManager.subscription.noBillingHistory")}
                      </td>
                    </tr>
                  ) : (
                    billingRecords.map((record, index) => (
                      <tr key={record.id} className="border-b border-gray-200 last:border-b-0 hover:bg-gray-50/50 transition">
                        <td className="px-5 py-4 text-sm text-gray-900">{index + 1}</td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{formatDate(record.date)}</td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{t("practiceManager.subscription.practiceManagers")}</td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{`$${record.amount}`}</td>
                        <td className="px-5 py-4 border-l border-gray-200">{getStatusBadge(record.status)}</td>
                        <td className="px-5 py-4 border-l border-gray-200">
                          <button
                            onClick={() => {
                              if (record.invoice_url) window.open(record.invoice_url, '_blank');
                              else if (record.invoice_pdf) window.open(record.invoice_pdf, '_blank');
                            }}
                            disabled={!record.invoice_url && !record.invoice_pdf}
                            className={`px-4 py-1.5 text-sm font-medium rounded-lg border transition ${
                              record.invoice_url || record.invoice_pdf
                                ? "border-gray-300 text-gray-700 hover:bg-gray-50 cursor-pointer"
                                : "border-gray-200 text-gray-400 cursor-not-allowed"
                            }`}
                          >
                            {t("practiceManager.subscription.invoice")}
                          </button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
              </div>
            </div>

            {/* Pagination */}
            {billingRecords.length > 0 && totalPages > 1 && (
              <div className="flex items-center justify-between mt-4">
                <button
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                  className="flex items-center gap-1 text-sm text-gray-600 hover:text-gray-900 disabled:text-gray-300 disabled:cursor-not-allowed cursor-pointer"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
                  </svg>
                  {t("practiceManager.common.previous")}
                </button>

                <div className="flex items-center gap-1">
                  {getPageNumbers().map((page, index) =>
                    page === "..." ? (
                      <span key={`ellipsis-${index}`} className="px-2 text-gray-400">...</span>
                    ) : (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page as number)}
                        className={`w-8 h-8 rounded-lg text-sm font-medium transition cursor-pointer ${
                          currentPage === page
                            ? "bg-[#3B9EC9] text-white"
                            : "text-gray-600 hover:bg-gray-100"
                        }`}
                      >
                        {page}
                      </button>
                    )
                  )}
                </div>

                <button
                  onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                  disabled={currentPage === totalPages}
                  className="flex items-center gap-1 text-sm text-gray-600 hover:text-gray-900 disabled:text-gray-300 disabled:cursor-not-allowed cursor-pointer"
                >
                  {t("practiceManager.common.next")}
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            )}
          </div>
        )}

        {/* Pricing Section */}
        <div className="text-center mb-10">
          <h2 className="text-3xl font-bold text-gray-900 mb-3">{t("practiceManager.subscription.simplePricing")}</h2>
          <p className="text-gray-500 max-w-xl mx-auto">
            {t("practiceManager.subscription.pricingSubtitle")}
          </p>
        </div>

        {/* Plans Error State */}
        {!!plansError && (
          <div className="bg-red-50 border border-red-200 rounded-2xl p-6 text-center mb-8">
            <p className="text-red-600 font-medium mb-2">{t("practiceManager.subscription.plansLoadError")}</p>
            <p className="text-red-500 text-sm mb-4">{t("practiceManager.subscription.plansLoadErrorRetry")}</p>
            <button
              onClick={() => refetchPlans()}
              className="inline-flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182" />
              </svg>
              {t("practiceManager.common.retry")}
            </button>
          </div>
        )}

        {/* Pricing Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Individual Plan Cards */}
            {individualPlans.map((plan, index) => {
              const isActivePlan = shouldDisableSubscribe && userData?.subscription_type !== 'group' && plan.planType === activePlanType;
              return (
                <div
                  key={index}
                  className={`bg-white rounded-2xl p-6 relative cursor-pointer hover:shadow-md transition-shadow ${
                    isActivePlan
                      ? "border-2 border-[#3B9EC9] shadow-lg"
                      : "border border-gray-200"
                  }`}
                >
                  {isActivePlan && (
                    <span className="absolute top-4 right-4 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-600">
                      <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
                      {t("practiceManager.subscription.activePlan")}
                    </span>
                  )}

                  {plan.planType === "annual" && plan.savings ? (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 mb-3 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                      <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M10 2L12.39 7.05L18 7.84L14 11.74L14.94 17.32L10 14.69L5.06 17.32L6 11.74L2 7.84L7.61 7.05L10 2Z" />
                      </svg>
                      {t("practiceManager.subscription.saveBadge", { amount: `$${plan.savings}` })}
                    </span>
                  ) : null}

                  {/* Price */}
                  <div className="flex items-baseline gap-1 mb-1">
                    <span className="text-3xl font-bold text-gray-900">{plan.price}</span>
                    <span className="text-sm text-gray-500">/{plan.period}</span>
                  </div>
                  <p className="text-xs text-gray-500 mb-2">
                    {plan.planType === "annual"
                      ? t("practiceManager.subscription.billedAnnually")
                      : t("practiceManager.subscription.billedMonthly")}
                  </p>
                  <p className="text-gray-600 mb-4">{plan.name}</p>
                  <p className="text-sm text-gray-500 mb-4">{plan.description}</p>

                  {/* Features */}
                  <div className="mb-6">
                    <p className="text-sm font-medium text-gray-900 mb-3">{t("practiceManager.subscription.whatsIncluded")}</p>
                    <ul className="space-y-2.5">
                      {plan.features.map((feature: string, featureIndex: number) => (
                        <li key={featureIndex} className="flex items-start gap-2 text-sm text-gray-600">
                          <CheckIcon />
                          {feature}
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* Button */}
                  <button
                    onClick={() => {
                      const cardId = `individual-${plan.planType}`;
                      if (shouldDisableSubscribe) {
                        if (isActivePlan) {
                          handlePortal(cardId);
                        } else {
                          toast.error(t("practiceManager.subscription.alreadyActiveError"), { duration: 4000 });
                        }
                      } else {
                        const currentData = getUserDataCookie();
                        if (currentData) {
                          setUserDataCookie({ ...currentData, subscription_type: 'individual' });
                        }
                        handleSubscribe(plan.planType, 'individual', cardId);
                      }
                    }}
                    disabled={!!pendingCard || isActivePlan}
                    className={`w-full py-3 rounded-lg text-sm font-medium transition flex items-center justify-center gap-2 disabled:cursor-default disabled:pointer-events-none ${
                      pendingCard === `individual-${plan.planType}`
                        ? "bg-[#3B9EC9]/60 text-white/80"
                        : isActivePlan
                        ? "bg-[#3B9EC9] text-white"
                        : !!pendingCard
                        ? "opacity-40 bg-[#3B9EC9] text-white"
                        : plan.buttonStyle === "filled"
                          ? "bg-[#3B9EC9] text-white hover:bg-[#2D8AB5] cursor-pointer"
                          : "border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 cursor-pointer"
                    }`}
                  >
                    {pendingCard === `individual-${plan.planType}` ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
                        {t("practiceManager.subscription.processing")}
                      </>
                    ) : isActivePlan ? (
                      <>
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                        </svg>
                        {t("practiceManager.subscription.currentPlan")}
                      </>
                    ) : (
                      <>
                        {shouldDisableSubscribe
                          ? t("practiceManager.subscription.upgradeNow")
                          : t("practiceManager.subscription.subscribeNow")}
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                        </svg>
                      </>
                    )}
                  </button>
                </div>
              );
            })}

            {/* Practice Manager Card with Monthly/Yearly Toggle */}
            {groupPlanData && (() => {
              const gp = groupPlanData;
              const pmPrice = pmBillingCycle === 'monthly' ? gp.priceMonthly : gp.priceYearly;
              const pmPeriod = pmBillingCycle === 'monthly' ? t("practiceManager.subscription.perMonth") : t("practiceManager.subscription.perYear");
              const pmFeatures = pmBillingCycle === 'monthly' ? gp.featuresMonthly : gp.featuresYearly;
              const pmButtonText = shouldDisableSubscribe
                ? t("practiceManager.subscription.upgradeNow")
                : t("practiceManager.subscription.subscribeNow");
              const isActivePM = shouldDisableSubscribe && userData?.subscription_type === 'group' && pmBillingCycle === activePlanType;
              return (
                <div className={`bg-white rounded-2xl p-6 relative cursor-pointer hover:shadow-md transition-shadow ${
                  isActivePM ? "border-2 border-[#3B9EC9] shadow-lg" : "border border-gray-200"
                }`}>
                  {isActivePM && (
                    <span className="absolute top-4 right-4 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-600">
                      <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
                      {t("practiceManager.subscription.activePlan")}
                    </span>
                  )}

                  {pmBillingCycle === 'annual' && gp.yearlySavings > 0 ? (
                    <div className="flex justify-center mb-3">
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                        <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M10 2L12.39 7.05L18 7.84L14 11.74L14.94 17.32L10 14.69L5.06 17.32L6 11.74L2 7.84L7.61 7.05L10 2Z" />
                        </svg>
                        {t("practiceManager.subscription.saveBadge", { amount: `$${gp.yearlySavings}` })}
                      </span>
                    </div>
                  ) : null}

                  {/* Monthly/Yearly Toggle */}
                  <div className="flex items-center justify-center gap-3 mb-4">
                    <span className={`text-sm font-medium transition ${pmBillingCycle === 'monthly' ? 'text-gray-900' : 'text-gray-400'}`}>{t("practiceManager.subscription.monthly")}</span>
                    <button
                      type="button"
                      onClick={() => setPmBillingCycle(pmBillingCycle === 'monthly' ? 'annual' : 'monthly')}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition cursor-pointer ${
                        pmBillingCycle === 'annual' ? 'bg-[#3B9EC9]' : 'bg-gray-300'
                      }`}
                    >
                      <span className={`inline-block h-4 w-4 rounded-full bg-white transition-transform ${
                        pmBillingCycle === 'annual' ? 'translate-x-6' : 'translate-x-1'
                      }`} />
                    </button>
                    <span className={`text-sm font-medium transition ${pmBillingCycle === 'annual' ? 'text-gray-900' : 'text-gray-400'}`}>{t("practiceManager.subscription.yearly")}</span>
                  </div>

                  {/* Price */}
                  <div className="flex items-baseline gap-1 mb-1">
                    <span className="text-3xl font-bold text-gray-900">{pmPrice || 'N/A'}</span>
                    <span className="text-sm text-gray-500">/{pmPeriod}</span>
                  </div>
                  <p className="text-gray-600 mb-4">{gp.name}</p>
                  <p className="text-sm text-gray-500 mb-4">{gp.description}</p>

                  {/* Features */}
                  <div className="mb-6">
                    <p className="text-sm font-medium text-gray-900 mb-3">{t("practiceManager.subscription.whatsIncluded")}</p>
                    <ul className="space-y-2.5">
                      {pmFeatures.map((feature: string, featureIndex: number) => (
                        <li key={featureIndex} className="flex items-start gap-2 text-sm text-gray-600">
                          <CheckIcon />
                          {feature}
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* Button */}
                  <button
                    onClick={() => {
                      if (shouldDisableSubscribe) {
                        if (isActivePM) {
                          handlePortal('group');
                        } else {
                          toast.error(t("practiceManager.subscription.alreadyActiveError"), { duration: 4000 });
                        }
                      } else {
                        const currentData = getUserDataCookie();
                        if (currentData) {
                          setUserDataCookie({ ...currentData, subscription_type: 'group' });
                        }
                        handleSubscribe(pmBillingCycle, 'group', 'group');
                      }
                    }}
                    disabled={!!pendingCard || isActivePM}
                    className={`w-full py-3 rounded-lg text-sm font-medium transition flex items-center justify-center gap-2 disabled:cursor-default disabled:pointer-events-none ${
                      pendingCard === 'group'
                        ? "bg-[#3B9EC9]/60 text-white/80"
                        : isActivePM
                        ? "bg-[#3B9EC9] text-white"
                        : !!pendingCard
                        ? "opacity-40 bg-[#3B9EC9] text-white"
                        : "bg-[#3B9EC9] text-white hover:bg-[#2D8AB5] cursor-pointer"
                    }`}
                  >
                    {pendingCard === 'group' ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
                        {t("practiceManager.subscription.processing")}
                      </>
                    ) : isActivePM ? (
                      <>
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                        </svg>
                        {t("practiceManager.subscription.currentPlan")}
                      </>
                    ) : (
                      <>
                        {pmButtonText}
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                        </svg>
                      </>
                    )}
                  </button>
                </div>
              );
            })()}
        </div>

        {/* Trust line below pricing cards */}
        <p className="mt-6 text-center text-sm text-gray-500">
          {t("practiceManager.subscription.noCreditCardRequired")}
        </p>
        </>
        )}
      </main>
    </>
  );
}

export default function PracticeManagerSubscription() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-gradient-to-br from-[#E8F4F8] via-[#EEF6F9] to-[#E5EEF2] flex items-center justify-center"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div></div>}>
      <PracticeManagerSubscriptionContent />
    </Suspense>
  );
}
