import { redirect } from 'next/navigation';
import Stripe from 'stripe';
import { prisma } from '@/lib/prisma';
import Link from 'next/link';
import Image from 'next/image';
import AutoReload from '../components/AutoReload';
import RefreshButton from '../components/RefreshButton';
import RegistrationLogoBar from '../components/RegistrationLogoBar';
import '@/app/styles/registration-theme.css';
import { getStripeClient } from '@/lib/stripe';

interface PageProps {
  searchParams: Promise<{
    session_id?: string;
    reload_count?: string;
  }>;
}

/**
 * Registration Welcome Page
 *
 * Landing page immediately after Stripe checkout.
 * Shows welcome message and allows user to continue to onboarding.
 *
 * Flow:
 * - Stripe checkout success → redirect to /registration/welcome?session_id=xxx
 * - Verify payment succeeded
 * - Check if dealer already exists and is active
 * - Show welcome message with continue button
 */
export default async function RegistrationWelcome(props: PageProps) {
  const searchParams = await props.searchParams;
  const sessionId = searchParams.session_id;
  const reloadCount = searchParams.reload_count ? parseInt(searchParams.reload_count as string) : 0;

  // Require session ID
  if (!sessionId) {
    redirect('/landing/');
  }

  // Retrieve session from Stripe
  let session: Stripe.Checkout.Session;
  try {
    const stripe = getStripeClient();
    session = await stripe.checkout.sessions.retrieve(sessionId);
  } catch (_error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="max-w-md w-full bg-white shadow-lg rounded-lg p-8">
          <h1 className="text-2xl font-bold text-red-600 mb-4">Session Not Found</h1>
          <p className="text-gray-600 mb-4">
            We couldn&apos;t find your checkout session. It may have expired.
          </p>
          <Link
            href="/"
            className="inline-block bg-sky-400 text-slate-900 font-semibold px-6 py-2 rounded-md hover:bg-sky-500 transition-colors"
          >
            Return to Home
          </Link>
        </div>
      </div>
    );
  }

  // Verify payment succeeded
  if (session.payment_status !== 'paid') {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="max-w-md w-full bg-white shadow-lg rounded-lg p-8">
          <h1 className="text-2xl font-bold text-red-600 mb-4">Payment Not Completed</h1>
          <p className="text-gray-600 mb-4">
            Your payment has not been processed yet. Please complete your checkout or contact
            support.
          </p>
          <Link
            href="/"
            className="inline-block bg-sky-400 text-slate-900 font-semibold px-6 py-2 rounded-md hover:bg-sky-500 transition-colors"
          >
            Return to Home
          </Link>
        </div>
      </div>
    );
  }

  // Check if dealer already exists
  const customerId = session.customer as string;
  const dealer = await prisma.dealer.findFirst({
    where: { stripeCustomerId: customerId },
  });

  // Dealer not found yet - webhook may be delayed
  if (!dealer) {
    // If we've waited too long (10 reloads = 30 seconds), show error
    if (reloadCount >= 10) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50">
          <div className="max-w-md w-full bg-white shadow-lg rounded-lg p-8">
            <h1 className="text-2xl font-bold text-red-600 mb-4">
              Account Setup Taking Longer Than Expected
            </h1>
            <p className="text-gray-600 mb-4">
              We&apos;re still processing your payment. This usually completes within a few seconds,
              but sometimes takes a bit longer.
            </p>
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
              <p className="text-sm text-gray-700 font-medium mb-2">What you can do:</p>
              <ul className="text-sm text-gray-600 space-y-1 list-disc list-inside">
                <li>Wait another minute and refresh this page</li>
                <li>Check your email for a confirmation from Stripe</li>
                <li>Contact support if the issue persists</li>
              </ul>
            </div>
            <div className="flex gap-3">
              <RefreshButton />
              <Link
                href="/"
                className="flex-1 text-center bg-gray-200 text-gray-700 px-6 py-2 rounded-md hover:bg-gray-300"
              >
                Return Home
              </Link>
            </div>
          </div>
        </div>
      );
    }

    // Still waiting - show loading screen and auto-reload
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="max-w-md w-full bg-white shadow-lg rounded-lg p-8 text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-sky-400 mx-auto mb-4"></div>
          <h1 className="text-2xl font-bold text-gray-800 mb-4">Setting up your account...</h1>
          <p className="text-sm font-semibold text-gray-700 mb-2">
            THIS USUALLY TAKES A FEW SECONDS
          </p>
          <p className="text-gray-600 mb-4">
            We&apos;re processing your payment and creating your dealer account.
          </p>
          <p className="text-sm text-gray-500">
            This page will automatically refresh when ready. ({reloadCount}/10)
          </p>
          <AutoReload delayMs={3000} />
        </div>
      </div>
    );
  }

  // Dealer already active or has completed registration - redirect to dashboard
  if (dealer.status === 'active' || dealer.status === 'registration_complete') {
    redirect('/dashboard');
  }

  // Get subscription tier info
  const tierMap: Record<string, string> = {
    starter: 'Starter',
    growth: 'Growth',
    enhanced: 'Enhanced',
    professional: 'Professional',
  };
  const _tierName = tierMap[dealer.subscriptionTier] || 'Starter';

  // Show welcome screen - Figma AMS_Page4_Option1 design
  return (
    <div
      className="min-h-screen flex flex-col overflow-hidden welcome-page-root"
      style={{ backgroundColor: 'var(--reg-bg-navy)' }}
    >
      {/* Logo Bar - Shared Component */}
      <RegistrationLogoBar />

      {/* Two-Column Layout */}
      <div className="flex-1 flex flex-col lg:flex-row welcome-two-column-layout relative lg:overflow-hidden">
        {/* Triangle Divider - Centered between columns */}
        <div
          className="absolute top-1/2 w-[84px] h-[76px] z-10 pointer-events-none"
          style={{
            left: 'calc(1/2 * 93%)',
            transform: 'translateY(-50%) rotate(90deg)',
          }}
        >
          <Image
            src="/media/icons/triangle-divider.svg"
            alt=""
            width={84}
            height={76}
            className="w-full h-full"
          />
        </div>

        {/* Left Column - Success Message */}
        <div className="w-full lg:w-1/2 flex flex-col justify-center px-8 lg:px-[92px] welcome-left-column lg:overflow-y-auto">
          {/* Success Checkmark Icon */}
          <div className="mb-6 welcome-success-icon">
            <Image
              src="/media/icons/success-checkmark.svg"
              alt=""
              width={80}
              height={80}
              className="w-20 h-20"
            />
          </div>

          {/* Payment Successful Heading */}
          <h1
            className="font-bold mb-[35px] welcome-main-heading"
            style={{
              color: 'var(--reg-text-white)',
              fontSize: '65px',
              lineHeight: '0.94',
              letterSpacing: '-1.3px',
              maxWidth: '378px',
            }}
          >
            Payment Successful!
          </h1>

          {/* Welcome Message */}
          <p
            className="font-normal welcome-subtitle"
            style={{
              color: 'var(--reg-text-white)',
              fontSize: '28px',
              lineHeight: '1.25',
              letterSpacing: '-0.56px',
              maxWidth: '316px',
            }}
          >
            Welcome to AMSOIL Dealer Pages!
          </p>
        </div>

        {/* Right Column - What's Next + Gradient Background */}
        <div
          className="w-full lg:w-1/2 flex items-center justify-center p-8 lg:p-12 min-h-[600px] welcome-right-column"
          style={{
            background: `linear-gradient(180deg, var(--reg-bg-slate) 0%, var(--reg-bg-gradient-end) 75.78%)`,
          }}
        >
          {/* Content Container */}
          <div className="w-full max-w-lg space-y-8 welcome-content-wrapper">
            {/* What Happens Next Heading */}
            <h2
              className="text-[36px] lg:text-[44px] font-normal leading-[1.05] welcome-checklist-heading"
              style={{ color: 'var(--reg-text-white)', letterSpacing: '-0.02em' }}
            >
              What Happens Next?
            </h2>

            {/* Checklist */}
            <div className="space-y-6 welcome-checklist">
              {/* Step 1 */}
              <div className="flex items-start gap-4 welcome-checklist-item">
                <div className="flex-shrink-0 mt-1">
                  <Image
                    src="/media/icons/checkmark-icon.svg"
                    alt=""
                    width={24}
                    height={24}
                    className="w-6 h-6"
                  />
                </div>
                <p
                  className="text-[18px] lg:text-[22px] font-normal leading-[1.3]"
                  style={{ color: 'var(--reg-text-white)' }}
                >
                  Choose your subdomain
                </p>
              </div>

              {/* Step 2 */}
              <div className="flex items-start gap-4 welcome-checklist-item">
                <div className="flex-shrink-0 mt-1">
                  <Image
                    src="/media/icons/checkmark-icon.svg"
                    alt=""
                    width={24}
                    height={24}
                    className="w-6 h-6"
                  />
                </div>
                <p
                  className="text-[18px] lg:text-[22px] font-normal leading-[1.3]"
                  style={{ color: 'var(--reg-text-white)' }}
                >
                  Set up your business profile
                </p>
              </div>

              {/* Step 3 */}
              <div className="flex items-start gap-4 welcome-checklist-item">
                <div className="flex-shrink-0 mt-1">
                  <Image
                    src="/media/icons/checkmark-icon.svg"
                    alt=""
                    width={24}
                    height={24}
                    className="w-6 h-6"
                  />
                </div>
                <p
                  className="text-[18px] lg:text-[22px] font-normal leading-[1.3]"
                  style={{ color: 'var(--reg-text-white)' }}
                >
                  Customize your page content (optional)
                </p>
              </div>

              {/* Step 4 */}
              <div className="flex items-start gap-4 welcome-checklist-item">
                <div className="flex-shrink-0 mt-1">
                  <Image
                    src="/media/icons/checkmark-icon.svg"
                    alt=""
                    width={24}
                    height={24}
                    className="w-6 h-6"
                  />
                </div>
                <p
                  className="text-[18px] lg:text-[22px] font-normal leading-[1.3]"
                  style={{ color: 'var(--reg-text-white)' }}
                >
                  Publish your site and go live!
                </p>
              </div>
            </div>

            {/* Continue to Setup Button */}
            <Link
              href={`/registration/onboarding?session_id=${sessionId}`}
              className="inline-flex items-center justify-center gap-[10px] rounded-[15px] transition-colors welcome-continue-button"
              style={{
                backgroundColor: 'var(--reg-accent-cyan)',
                height: '50px',
                paddingLeft: '18px',
                paddingRight: '18px',
                width: 'fit-content',
              }}
            >
              <span
                className="font-bold uppercase text-center"
                style={{
                  color: 'var(--reg-bg-navy)',
                  fontSize: '16px',
                  lineHeight: '1.15',
                  letterSpacing: '-0.32px',
                  maxWidth: '202px',
                }}
              >
                Continue to setup
              </span>
              {/* Arrow Icon */}
              <div
                className="flex items-center justify-center"
                style={{ transform: 'rotate(90deg)' }}
              >
                <svg
                  width="15"
                  height="9"
                  viewBox="0 0 15 9"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M1 1L7.5 7.5L14 1"
                    stroke="var(--reg-bg-navy)"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </div>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
