"use client";

import { useEffect, useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { getUserDataCookie, setUserDataCookie } from "@/lib/cookies";
import { useSubscriptionControllerGetSubscriptionStatusV1 } from "@/api/user/practitioner-subscription/practitioner-subscription";

export default function SubscriptionSuccessPage() {
  const t = useTranslations();
  const [status, setStatus] = useState<"loading" | "success" | "error">("loading");
  const [retryCount, setRetryCount] = useState(0);

  // Use getSubscriptionStatus which triggers auto-verify with Stripe if INCOMPLETE
  const { data: subData, error, isLoading, refetch } = useSubscriptionControllerGetSubscriptionStatusV1({
    query: {
      retry: 15,
      retryDelay: 3000,
      refetchInterval: status === "loading" ? 3000 : false,
    },
  });

  useEffect(() => {
    if (isLoading) return;

    const subStatus = (subData as any)?.data?.status;
    const subType = (subData as any)?.data?.subscription_type;

    // Subscription is active — update cookie and redirect
    if (subStatus === "active") {
      const current = getUserDataCookie();
      if (current) {
        setUserDataCookie({ ...current, has_active_subscription: true, subscription_type: subType || current.subscription_type });
      }
      setStatus("success");

      const timer = setTimeout(() => {
        const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
        if (subType === 'group') {
          window.location.href = `${basePath}/practice-manager/dashboard`;
        } else {
          window.location.href = `${basePath}/practitioner`;
        }
      }, 2000);
      return () => clearTimeout(timer);
    }

    // Only show error after enough polling attempts (give webhook + auto-verify time to process)
    if (error || subData) {
      if (retryCount < 15) {
        setRetryCount((prev) => prev + 1);
      } else {
        setStatus("error");
      }
    }
  }, [subData, error, isLoading, retryCount]);

  const handleRetry = useCallback(() => {
    setStatus("loading");
    setRetryCount(0);
    refetch();
  }, [refetch]);

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-lg mx-auto px-4 sm:px-6 lg:px-8">
        <div className="bg-white rounded-2xl border border-gray-100 p-8 text-center">
          {status === "loading" && (
            <>
              <div className="mx-auto mb-4 w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#3B9EC9]"></div>
              </div>
              <h1 className="text-xl font-semibold text-gray-900 mb-2">
                {t("practitioner.subscription.verifyingPayment")}
              </h1>
              <p className="text-gray-500 text-sm">
                {t("practitioner.subscription.pleaseWait")}
              </p>
            </>
          )}

          {status === "success" && (
            <>
              <div className="mx-auto mb-4 w-12 h-12 rounded-full bg-green-50 flex items-center justify-center">
                <svg className="w-6 h-6 text-green-500" 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>
              </div>
              <h1 className="text-xl font-semibold text-gray-900 mb-2">
                {t("practitioner.subscription.paymentSuccessful")}
              </h1>
              <p className="text-gray-500 text-sm">
                {t("practitioner.subscription.redirectingToDashboard")}
              </p>
            </>
          )}

          {status === "error" && (
            <>
              <div className="mx-auto mb-4 w-12 h-12 rounded-full bg-red-50 flex items-center justify-center">
                <svg className="w-6 h-6 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </div>
              <h1 className="text-xl font-semibold text-gray-900 mb-2">
                {t("practitioner.subscription.verificationFailed")}
              </h1>
              <p className="text-gray-500 text-sm mb-6">
                {t("practitioner.subscription.verificationFailedDesc")}
              </p>
              <div className="flex flex-col gap-3">
                <button
                  onClick={handleRetry}
                  className="inline-flex items-center justify-center gap-2 px-6 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("practitioner.common.retry")}
                </button>
                <a
                  href={`${process.env.NEXT_PUBLIC_BASE_PATH || ""}/practitioner/subscription`}
                  className="inline-flex items-center justify-center px-6 py-2.5 text-sm font-medium text-[#3B9EC9] bg-white border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition"
                >
                  {t("practitioner.subscription.goToSubscription")}
                </a>
              </div>
            </>
          )}
        </div>
      </div>
    </main>
  );
}
