"use client";

import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { Loader2, CheckCircle, AlertCircle } from "lucide-react";
import type { Lang } from "@/lib/config";

const POLL_INTERVAL = 2000; // 2 seconds
const MAX_ATTEMPTS = 15; // 30 seconds total (increased for webhook processing)

type Status = "loading" | "success" | "error";

interface Translation {
  title: string;
  loading: string;
  success: string;
  error: string;
  redirecting: string;
  retryButton: string;
  dashboardButton: string;
  attemptText: string;
  sessionIdLabel: string;
}

const translations: Record<string, Translation> = {
  en: {
    title: "Processing Your Payment",
    loading: "Please wait while we confirm your subscription...",
    success: "Payment Successful! Your subscription is now active.",
    error:
      "Unable to confirm subscription. Please contact support if you were charged.",
    redirecting: "Redirecting to dashboard...",
    retryButton: "Retry",
    dashboardButton: "Go to Dashboard",
    attemptText: "Attempt",
    sessionIdLabel: "Session ID: ",
  },
  ar: {
    title: "معالجة الدفع",
    loading: "يرجى الانتظار بينما نؤكد اشتراكك...",
    success: "تم الدفع بنجاح! اشتراكك نشط الآن.",
    error: "تعذر تأكيد الاشتراك. يرجى الاتصال بالدعم إذا تم خصم المبلغ.",
    redirecting: "إعادة التوجيه إلى لوحة التحكم...",
    retryButton: "إعادة المحاولة",
    dashboardButton: "الذهاب إلى لوحة التحكم",
    attemptText: "محاولة",
    sessionIdLabel: "معرف الجلسة: ",
  },
};

interface SubscriptionSuccessContentProps {
  lang: Lang;
  sessionId?: string;
  bookingId?: string;
}

export default function SubscriptionSuccessContent({
  lang,
  sessionId,
  bookingId,
}: SubscriptionSuccessContentProps) {
  const router = useRouter();
  const [status, setStatus] = useState<Status>("loading");
  const [attempts, setAttempts] = useState(0);
  const [redirecting, setRedirecting] = useState(false);

  const t = translations[lang] || translations.en;
  const isRTL = lang === "ar";

  // Track if we've already verified the session
  const hasVerified = useRef(false);

  useEffect(() => {
    // If no session_id, show error immediately
    if (!sessionId) {
      setStatus("error");
      return;
    }

    let isMounted = true;
    let pollTimeout: NodeJS.Timeout;

    // First, try to verify and sync the session (creates subscription if webhook hasn't)
    const verifySession = async () => {
      if (hasVerified.current) return false;

      try {
        console.log("[SubscriptionSuccess] Verifying session:", sessionId);
        const response = await fetch(
          `/api/payment/verify-session?session_id=${sessionId}`,
          {
            method: "GET",
            credentials: "include",
          },
        );

        if (!response.ok) {
          console.warn(
            "[SubscriptionSuccess] Verify session failed:",
            response.status,
          );
          return false;
        }

        const result = await response.json();
        hasVerified.current = true;

        if (result.success && result.hasActiveSubscription) {
          console.log(
            "[SubscriptionSuccess] Session verified, subscription active",
          );
          return true;
        }

        console.log("[SubscriptionSuccess] Verify result:", result);
        return false;
      } catch (error) {
        console.error("[SubscriptionSuccess] Verify error:", error);
        return false;
      }
    };

    const pollSubscriptionStatus = async () => {
      // Check if we've exceeded max attempts
      if (attempts >= MAX_ATTEMPTS) {
        if (isMounted) {
          setStatus("error");
        }
        return;
      }

      try {
        // On first attempt, verify the session (creates subscription if needed)
        if (attempts === 0) {
          const verified = await verifySession();
          if (verified && isMounted) {
            setStatus("success");
            setRedirecting(true);
            setTimeout(() => {
              if (isMounted) {
                router.push(`/${lang}/dashboard`);
              }
            }, 2000);
            return;
          }
        }

        // Poll subscription status
        const response = await fetch("/api/subscription/status", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
          credentials: "include",
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const result = await response.json();

        if (!isMounted) return;

        // Check if subscription is active
        if (result.success && result.data?.hasActiveSubscription) {
          setStatus("success");
          setRedirecting(true);

          // Redirect to dashboard after 2 seconds
          setTimeout(() => {
            if (isMounted) {
              router.push(`/${lang}/dashboard`);
            }
          }, 2000);
        } else {
          // Increment attempts and schedule next poll
          setAttempts((prev) => prev + 1);

          if (attempts + 1 < MAX_ATTEMPTS) {
            pollTimeout = setTimeout(pollSubscriptionStatus, POLL_INTERVAL);
          } else {
            setStatus("error");
          }
        }
      } catch (error) {
        console.error("Error polling subscription status:", error);

        if (!isMounted) return;

        // Increment attempts and try again
        setAttempts((prev) => prev + 1);

        if (attempts + 1 < MAX_ATTEMPTS) {
          pollTimeout = setTimeout(pollSubscriptionStatus, POLL_INTERVAL);
        } else {
          setStatus("error");
        }
      }
    };

    // Start polling immediately
    pollSubscriptionStatus();

    // Cleanup function
    return () => {
      isMounted = false;
      if (pollTimeout) {
        clearTimeout(pollTimeout);
      }
    };
  }, [sessionId, attempts, lang, router]);

  const handleRetry = () => {
    setStatus("loading");
    setAttempts(0);
    setRedirecting(false);
  };

  const handleGoToDashboard = () => {
    router.push(`/${lang}/dashboard`);
  };

  return (
    <div
      className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800 px-4"
      dir={isRTL ? "rtl" : "ltr"}
    >
      <div className="max-w-md w-full bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            {t.title}
          </h1>
        </div>

        {/* Status Content */}
        <div className="flex flex-col items-center justify-center space-y-6">
          {/* Loading State */}
          {status === "loading" && (
            <>
              <div className="relative">
                <Loader2
                  className="w-20 h-20 text-blue-600 dark:text-blue-400 animate-spin"
                  strokeWidth={2}
                />
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="w-16 h-16 bg-blue-100 dark:bg-blue-900 rounded-full opacity-20 animate-ping" />
                </div>
              </div>

              <div className="text-center space-y-2">
                <p className="text-lg text-gray-700 dark:text-gray-300 font-medium">
                  {t.loading}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {isRTL
                    ? `${t.attemptText} ${attempts + 1} من ${MAX_ATTEMPTS}`
                    : `${t.attemptText} ${attempts + 1} of ${MAX_ATTEMPTS}`}
                </p>
              </div>

              {/* Progress Bar */}
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
                <div
                  className="bg-blue-600 dark:bg-blue-400 h-2 rounded-full transition-all duration-500 ease-out"
                  style={{ width: `${((attempts + 1) / MAX_ATTEMPTS) * 100}%` }}
                />
              </div>
            </>
          )}

          {/* Success State */}
          {status === "success" && (
            <>
              <div className="relative">
                <CheckCircle
                  className="w-20 h-20 text-green-600 dark:text-green-400"
                  strokeWidth={2}
                />
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="w-24 h-24 bg-green-100 dark:bg-green-900 rounded-full opacity-20 animate-pulse" />
                </div>
              </div>

              <div className="text-center space-y-2">
                <p className="text-lg text-gray-700 dark:text-gray-300 font-medium">
                  {t.success}
                </p>
                {redirecting && (
                  <div className="flex items-center justify-center space-x-2 rtl:space-x-reverse">
                    <Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {t.redirecting}
                    </p>
                  </div>
                )}
              </div>
            </>
          )}

          {/* Error State */}
          {status === "error" && (
            <>
              <div className="relative">
                <AlertCircle
                  className="w-20 h-20 text-red-600 dark:text-red-400"
                  strokeWidth={2}
                />
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="w-24 h-24 bg-red-100 dark:bg-red-900 rounded-full opacity-20 animate-pulse" />
                </div>
              </div>

              <div className="text-center space-y-4">
                <p className="text-lg text-gray-700 dark:text-gray-300 font-medium">
                  {t.error}
                </p>

                <div className="flex flex-col space-y-2">
                  <button
                    onClick={handleGoToDashboard}
                    className="w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 text-white font-semibold rounded-lg transition-colors duration-200 shadow-md hover:shadow-lg"
                  >
                    {t.dashboardButton}
                  </button>

                  <button
                    onClick={handleRetry}
                    className="w-full px-6 py-3 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 font-semibold rounded-lg transition-colors duration-200"
                  >
                    {t.retryButton}
                  </button>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Session ID (for debugging) */}
        {sessionId && (
          <div className="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
            <p className="text-xs text-gray-500 dark:text-gray-400 text-center break-all">
              {t.sessionIdLabel}
              <span className="font-mono">{sessionId}</span>
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
