"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useUser } from "@clerk/nextjs";
import { SITE, UI, type Lang } from "@/lib/config";
import { signupStorage } from "@/lib/storage";
import {
  CheckCircleIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/solid";
import {
  EnvelopeIcon,
  BuildingOfficeIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";
import { logger } from "@/lib/logger";
import { identifyUser, trackHighValueEvent } from "@/lib/posthog";

export default function SignupSuccessPage({
  params,
}: {
  params: { lang: Lang };
}) {
  const { lang } = params;
  const router = useRouter();
  const searchParams = useSearchParams();
  const sessionId = searchParams.get("session_id");
  const dir = UI[lang].dir;
  const { user: clerkUser } = useUser();

  const [status, setStatus] = useState<"verifying" | "success" | "error">(
    "verifying",
  );
  const [userData, setUserData] = useState<{
    email: string;
    fullName: string;
    companyName?: string;
  } | null>(null);
  const [subscriptionData, setSubscriptionData] = useState<{
    tierId?: string;
    billingPeriod?: string;
    currency?: string;
    amount?: number;
    setupFeeAmount?: number;
    trialDays?: number;
    goals?: string[];
  } | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const verifyPaymentAndComplete = async () => {
      try {
        // Get signup data (may be empty for Clerk-authenticated users)
        const signupData = signupStorage.get();

        // Set user data immediately — prefer Clerk user, fall back to signupStorage
        const clerkEmail = clerkUser?.emailAddresses[0]?.emailAddress;
        const clerkName = [clerkUser?.firstName, clerkUser?.lastName]
          .filter(Boolean)
          .join(" ");
        setUserData({
          email: clerkEmail || signupData?.email || "user@example.com",
          fullName: clerkName || signupData?.fullName || "User",
          companyName: signupData?.companyInfo?.companyName,
        });

        // If no session ID, redirect back to signup (payment required)
        if (!sessionId) {
          logger.warn("No session_id in success URL - redirecting to signup");
          setError(
            "No payment session found. Please complete the signup process.",
          );
          setStatus("error");
          return;
        }

        // Verify payment with backend
        logger.info("Verifying Stripe checkout session", { sessionId });
        const response = await fetch(
          `/api/signup/success?session_id=${sessionId}`,
        );

        if (!response.ok) {
          const error = await response.json();
          throw new Error(error.error || "Payment verification failed");
        }

        const result = await response.json();

        // Success!
        logger.info("Payment verified and subscription created", {
          subscriptionId: result.subscriptionId,
          redirectUrl: result.redirectUrl,
          sessionData: result.sessionData,
        });

        // Update user data with server response (has company name from Prisma)
        if (result.userData) {
          setUserData((prev) => ({
            email:
              prev?.email && prev.email !== "user@example.com"
                ? prev.email
                : result.userData.email,
            fullName:
              prev?.fullName && prev.fullName !== "User"
                ? prev.fullName
                : result.userData.fullName,
            companyName:
              prev?.companyName || result.userData.companyName || undefined,
          }));
        }

        // Use ACTUAL pricing data from Stripe session (not hardcoded!)
        const sessionData = result.sessionData;
        setSubscriptionData({
          tierId: sessionData?.tierId || signupData?.plan?.tierId || "tier2",
          billingPeriod:
            sessionData?.billingPeriod ||
            signupData?.plan?.billingPeriod ||
            "monthly",
          currency:
            sessionData?.currency || signupData?.plan?.currency || "QAR",
          amount: sessionData?.recurringAmount || 0, // ACTUAL amount from Stripe
          setupFeeAmount: sessionData?.setupFeeAmount || 0,
          trialDays: sessionData?.trialDays || 14,
          goals: signupData?.goals,
        });

        setStatus("success");

        // Identify user in PostHog with subscription details
        if (result.userId || signupData?.email) {
          identifyUser(result.userId || signupData?.email || "", {
            email: signupData?.email,
            name: signupData?.fullName,
            organizationId: signupData?.companyInfo?.companyName,
            package: sessionData?.tierId || signupData?.plan?.tierId,
            locale: lang,
          });

          // Track high-value signup completion event
          trackHighValueEvent("signup_completed", {
            tierId: sessionData?.tierId || signupData?.plan?.tierId,
            billingPeriod:
              sessionData?.billingPeriod || signupData?.plan?.billingPeriod,
            currency: sessionData?.currency || signupData?.plan?.currency,
            amount: sessionData?.recurringAmount || 0,
            setupFeeAmount: sessionData?.setupFeeAmount || 0,
            trialDays: sessionData?.trialDays || 14,
            hasCompanyInfo: !!signupData?.companyInfo?.companyName,
            goals: signupData?.goals,
          });
        }

        // Mark payment as succeeded and clear sensitive payment tracking data
        signupStorage.setPaymentStatus("succeeded");
        signupStorage.clearPaymentData();

        // Auto-redirect after a short delay
        setTimeout(() => {
          router.push(result.redirectUrl);
        }, 3000);
      } catch (err) {
        const errorMessage =
          err instanceof Error ? err.message : "An error occurred";
        logger.error("Payment verification failed", { error: errorMessage });

        // Track payment failure with error details for recovery
        signupStorage.setPaymentStatus("failed", errorMessage);

        setError(errorMessage);
        setStatus("error");
      }
    };

    verifyPaymentAndComplete();
    // clerkUser provides name/email; sessionId triggers verification
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId, router, clerkUser?.id]);

  if (!userData) {
    return null;
  }

  // Verifying state - show loading
  if (status === "verifying") {
    return (
      <main
        className="mx-auto flex min-h-screen items-center justify-center px-4 py-16"
        dir={dir}
      >
        <div className="w-full max-w-2xl space-y-8 text-center">
          <div className="flex justify-center">
            <div className="rounded-full bg-blue-50 p-4">
              <div className="h-20 w-20 animate-spin rounded-full border-4 border-blue-200 border-t-blue-500" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-brand-ink">
            {lang === "ar" ? "جاري التحقق من الدفع..." : "Verifying Payment..."}
          </h1>
          <p className="text-neutral-600">
            {lang === "ar"
              ? "يرجى الانتظار أثناء معالجة اشتراكك"
              : "Please wait while we process your subscription"}
          </p>
        </div>
      </main>
    );
  }

  // Error state - show error message
  if (status === "error") {
    return (
      <main
        className="mx-auto flex min-h-screen items-center justify-center px-4 py-16"
        dir={dir}
      >
        <div className="w-full max-w-2xl space-y-8">
          <div className="flex justify-center">
            <div className="rounded-full bg-red-50 p-4">
              <ExclamationTriangleIcon className="h-20 w-20 text-red-500" />
            </div>
          </div>

          <div className="space-y-3 text-center">
            <h1 className="text-3xl font-bold text-brand-ink">
              {lang === "ar" ? "خطأ في المعالجة" : "Processing Error"}
            </h1>
            <p className="text-lg text-neutral-600">{error}</p>
          </div>

          <div className="rounded-lg border border-red-200 bg-red-50 p-6">
            <p className="mb-4 text-sm text-neutral-700">
              {lang === "ar"
                ? "حدث خطأ أثناء معالجة اشتراكك. يرجى التواصل معنا للمساعدة:"
                : "There was an error processing your subscription. Please contact us for assistance:"}
            </p>
            <div className="flex flex-col gap-3">
              <a
                href={`mailto:${SITE.contact.email}`}
                className="text-sm font-semibold text-red-600 hover:text-red-700"
              >
                📧 {SITE.contact.email}
              </a>
              <a
                href={`https://wa.me/${SITE.contact.whatsapp.replace(/[^0-9]/g, "")}`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm font-semibold text-red-600 hover:text-red-700"
              >
                💬 {lang === "ar" ? "واتساب" : "WhatsApp"}
              </a>
            </div>
          </div>

          <div className="flex flex-col gap-4">
            <button
              onClick={() => {
                // Check if can resume from previous step
                const retryInfo = signupStorage.getPaymentRetryInfo();
                if (retryInfo) {
                  // Resume from step where payment failed
                  const stepRoutes: Record<number, string> = {
                    1: `/${lang}/signup`,
                    2: `/${lang}/signup/verify`,
                    3: `/${lang}/signup/company-info`,
                    4: `/${lang}/signup/company-info`, // Additional company info
                    5: `/${lang}/signup/onboarding`,
                    6: `/${lang}/signup/onboarding`, // Payment attempt
                  };
                  router.push(stepRoutes[retryInfo.step] || `/${lang}/signup`);
                } else {
                  // New signup
                  router.push(`/${lang}/signup`);
                }
              }}
              className="rounded-lg bg-brand-green px-8 py-3 text-center font-semibold text-white transition-all hover:bg-green-600"
            >
              {lang === "ar" ? "العودة للتسجيل" : "Back to Signup"}
            </button>
            <Link
              href={`/${lang}`}
              className="rounded-lg border-2 border-neutral-200 px-8 py-3 text-center font-semibold text-neutral-700 transition-all hover:border-neutral-300 hover:bg-neutral-50"
            >
              {lang === "ar" ? "العودة إلى الرئيسية" : "Back to Home"}
            </Link>
          </div>
        </div>
      </main>
    );
  }

  // Success state - show confirmation and redirect
  return (
    <main
      className="mx-auto flex min-h-screen items-center justify-center px-4 py-16"
      dir={dir}
    >
      <div className="w-full max-w-2xl space-y-8">
        {/* Success Icon */}
        <div className="flex justify-center">
          <div className="rounded-full bg-green-50 p-4">
            <CheckCircleIcon className="h-20 w-20 text-green-500" />
          </div>
        </div>

        {/* Header */}
        <div className="space-y-3 text-center">
          <h1 className="text-4xl font-extrabold text-brand-ink">
            {lang === "ar" ? "🎉 تهانينا!" : "🎉 Congratulations!"}
          </h1>
          <p className="text-xl text-neutral-600">
            {lang === "ar"
              ? "لقد أكملت عملية التسجيل بنجاح!"
              : "You have successfully completed the signup process!"}
          </p>
        </div>

        {/* Account & Subscription Card */}
        <div className="rounded-2xl border border-neutral-200 bg-white p-8 shadow-sm">
          <div className="space-y-6">
            {/* Welcome Message */}
            <div className="space-y-2">
              <h2 className="text-2xl font-bold text-brand-ink">
                {lang === "ar"
                  ? `مرحباً ${userData.fullName}!`
                  : `Welcome, ${userData.fullName}!`}
              </h2>
              <p className="text-neutral-600">
                {lang === "ar"
                  ? "شكراً لك على اختيار منصتنا. اشتراكك نشط الآن."
                  : "Thank you for choosing us. Your subscription is now active."}
              </p>
            </div>

            {/* Account Details */}
            <div className="space-y-4 border-t border-neutral-100 pt-6">
              <div className="flex items-start gap-3">
                <EnvelopeIcon className="h-6 w-6 text-brand-green" />
                <div>
                  <p className="text-sm font-medium text-neutral-500">
                    {lang === "ar" ? "البريد الإلكتروني" : "Email Address"}
                  </p>
                  <p className="font-semibold text-brand-ink">
                    {userData.email}
                  </p>
                </div>
              </div>

              {userData.companyName && (
                <div className="flex items-start gap-3">
                  <BuildingOfficeIcon className="h-6 w-6 text-brand-green" />
                  <div>
                    <p className="text-sm font-medium text-neutral-500">
                      {lang === "ar" ? "الشركة" : "Company"}
                    </p>
                    <p className="font-semibold text-brand-ink">
                      {userData.companyName}
                    </p>
                  </div>
                </div>
              )}
            </div>

            {/* Subscription Summary */}
            {subscriptionData && (
              <div className="space-y-4 border-t border-neutral-100 pt-6">
                <h3 className="font-semibold text-brand-ink">
                  {lang === "ar" ? "تفاصيل الاشتراك" : "Subscription Details"}
                </h3>
                <div className="grid grid-cols-2 gap-4">
                  {subscriptionData.tierId && (
                    <div>
                      <p className="text-xs font-medium text-neutral-500 uppercase">
                        {lang === "ar" ? "الباقة" : "Plan"}
                      </p>
                      <p className="mt-1 font-semibold text-brand-ink">
                        {subscriptionData.tierId.charAt(0).toUpperCase() +
                          subscriptionData.tierId.slice(1)}
                      </p>
                    </div>
                  )}
                  {subscriptionData.billingPeriod && (
                    <div>
                      <p className="text-xs font-medium text-neutral-500 uppercase">
                        {lang === "ar" ? "الفترة" : "Billing Period"}
                      </p>
                      <p className="mt-1 font-semibold text-brand-ink capitalize">
                        {subscriptionData.billingPeriod === "monthly"
                          ? lang === "ar"
                            ? "شهري"
                            : "Monthly"
                          : lang === "ar"
                            ? "سنوي"
                            : "Yearly"}
                      </p>
                    </div>
                  )}
                  {subscriptionData.currency && (
                    <div>
                      <p className="text-xs font-medium text-neutral-500 uppercase">
                        {lang === "ar" ? "العملة" : "Currency"}
                      </p>
                      <p className="mt-1 font-semibold text-brand-ink">
                        {subscriptionData.currency}
                      </p>
                    </div>
                  )}
                  <div>
                    <p className="text-xs font-medium text-neutral-500 uppercase">
                      {lang === "ar" ? "رسوم الإعداد" : "Setup Fee"}
                    </p>
                    <p className="mt-1 font-semibold text-brand-green">
                      {lang === "ar" ? "مشمولة" : "Included"}
                    </p>
                  </div>
                </div>

                {/* Payment Amount After Trial */}
                {subscriptionData.amount !== undefined &&
                  subscriptionData.amount > 0 && (
                    <div className="rounded-lg border-2 border-brand-green/30 bg-brand-green/5 p-4">
                      <div className="text-center">
                        <p className="text-sm font-medium text-neutral-600 mb-2">
                          {lang === "ar"
                            ? `المبلغ بعد الفترة التجريبية (${subscriptionData.trialDays || 14} يوم)`
                            : `Amount After ${subscriptionData.trialDays || 14}-Day Free Trial`}
                        </p>
                        <p className="text-3xl font-bold text-brand-green">
                          {subscriptionData.currency}{" "}
                          {subscriptionData.amount.toFixed(2)}
                          <span className="text-base font-normal text-neutral-600">
                            /
                            {subscriptionData.billingPeriod === "monthly"
                              ? lang === "ar"
                                ? "شهر"
                                : "month"
                              : lang === "ar"
                                ? "سنة"
                                : "year"}
                          </span>
                        </p>
                        <p className="text-xs text-neutral-500 mt-2">
                          {lang === "ar"
                            ? "سيتم تحصيل الرسوم تلقائياً بعد انتهاء الفترة التجريبية"
                            : "You will be charged automatically after your trial ends"}
                        </p>
                        {subscriptionData.setupFeeAmount &&
                          subscriptionData.setupFeeAmount > 0 && (
                            <p className="text-xs text-neutral-500 mt-2 border-t border-neutral-200 pt-2">
                              {lang === "ar"
                                ? `رسوم الإعداد المدفوعة: ${subscriptionData.currency} ${subscriptionData.setupFeeAmount.toFixed(2)}`
                                : `Setup fee paid: ${subscriptionData.currency} ${subscriptionData.setupFeeAmount.toFixed(2)}`}
                            </p>
                          )}
                      </div>
                    </div>
                  )}
                {subscriptionData.goals &&
                  subscriptionData.goals.length > 0 && (
                    <div className="rounded-lg bg-brand-green/5 p-4">
                      <p className="mb-2 text-sm font-medium text-brand-ink">
                        {lang === "ar" ? "أهدافك:" : "Your Goals:"}
                      </p>
                      <ul className="flex flex-wrap gap-2">
                        {subscriptionData.goals.map((goal) => (
                          <li
                            key={goal}
                            className="rounded-full bg-brand-green/10 px-3 py-1 text-xs font-medium text-brand-green"
                          >
                            {goal.replace(/_/g, " ")}
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
              </div>
            )}

            {/* What's Next */}
            <div className="space-y-3 rounded-lg bg-brand-green/5 p-6">
              <h3 className="font-semibold text-brand-ink">
                {lang === "ar" ? "ما التالي:" : "What's Next:"}
              </h3>
              <ul className="space-y-2 text-sm text-neutral-600">
                <li className="flex items-start gap-2">
                  <SparklesIcon className="h-5 w-5 flex-shrink-0 text-brand-green" />
                  <span>
                    {lang === "ar"
                      ? `تتمتع بـ ${subscriptionData?.trialDays || 14} يوم تجربة مجانية`
                      : `Enjoy ${subscriptionData?.trialDays || 14} days free trial`}
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <SparklesIcon className="h-5 w-5 flex-shrink-0 text-brand-green" />
                  <span>
                    {lang === "ar"
                      ? "سيتواصل معك فريقنا عبر البريد الإلكتروني خلال 24 ساعة"
                      : "Our team will contact you via email within 24 hours"}
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <SparklesIcon className="h-5 w-5 flex-shrink-0 text-brand-green" />
                  <span className="font-semibold text-brand-green">
                    {lang === "ar"
                      ? "انقر أدناه لتسجيل الدخول والوصول إلى لوحة التحكم"
                      : "Click below to log in and access your dashboard"}
                  </span>
                </li>
              </ul>
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex flex-col gap-4 sm:flex-row sm:justify-center">
          <button
            onClick={() => router.push(`/${lang}/dashboard`)}
            className="rounded-lg bg-brand-green px-8 py-3 text-center text-sm font-semibold text-white transition-all hover:bg-brand-greenHover"
          >
            {lang === "ar" ? "تسجيل الدخول الآن" : "Log In Now"}
          </button>

          <Link
            href={`/${lang}`}
            className="rounded-lg border-2 border-neutral-200 px-8 py-3 text-center text-sm font-semibold text-neutral-700 transition-all hover:border-neutral-300 hover:bg-neutral-50"
          >
            {lang === "ar" ? "العودة إلى الرئيسية" : "Back to Home"}
          </Link>
        </div>

        {/* Support Info */}
        <div className="rounded-lg border border-brand-green/20 bg-brand-green/5 p-6 text-center">
          <p className="text-sm text-neutral-600">
            {lang === "ar"
              ? "لديك استفسار؟ تواصل معنا على"
              : "Have questions? Contact us at"}
          </p>
          <a
            href={`mailto:${SITE.contact.email}`}
            className="mt-1 font-semibold text-brand-green hover:text-brand-greenHover"
          >
            {SITE.contact.email}
          </a>
          <span className="mx-2 text-neutral-400">|</span>
          <a
            href={`https://wa.me/${SITE.contact.whatsapp.replace(/[^0-9]/g, "")}`}
            target="_blank"
            rel="noopener noreferrer"
            className="font-semibold text-brand-green hover:text-brand-greenHover"
          >
            {lang === "ar" ? "واتساب" : "WhatsApp"}
          </a>
        </div>

        {/* Branding */}
        <div className="text-center">
          <Link href={`/${lang}`} className="inline-block">
            <img src="/mawidi-icon.svg" alt="Mawidi" className="h-12 w-auto mx-auto" width={48} height={48} />
          </Link>
          <p className="mt-1 text-sm text-neutral-500">
            {lang === "ar"
              ? "إدارة المواعيد عبر واتساب"
              : "Appointment Management via WhatsApp"}
          </p>
        </div>
      </div>
    </main>
  );
}
