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

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

/**
 * Registration Onboarding Page
 *
 * Multi-step form for subdomain selection and profile setup.
 *
 * Flow:
 * - User arrives from welcome page with session_id
 * - Verify payment and dealer status
 * - Show multi-step form:
 *   1. Subdomain selection (required)
 *   2. Business profile
 *   3. Review & Publish
 */
export default async function RegistrationOnboarding(props: PageProps) {
  const searchParams = await props.searchParams;
  const sessionId = searchParams.session_id;

  // 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.</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>
    );
  }

  // Look up dealer by Stripe customer ID
  const customerId = session.customer as string;
  const dealer = await prisma.dealer.findFirst({
    where: { stripeCustomerId: customerId },
    include: { user: true },
  });

  // Dealer not found yet - webhook may be delayed
  if (!dealer) {
    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-gray-600 mb-4">
            We&apos;re processing your payment and creating your dealer account.
          </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');
  }

  // Show onboarding form
  return (
    <OnboardingForm
      dealerId={dealer.id}
      sessionId={sessionId}
      subscriptionTier={dealer.subscriptionTier}
      defaultDomain={dealer.domain}
      hasSubdomain={!!dealer.subdomain}
      initialData={{
        subdomain: dealer.subdomain || '',
        customDomain: dealer.customDomain || '',
        dealerNumber: dealer.dealerNumber || '',
        name: dealer.businessName || dealer.user.name || '',
        email: dealer.contactEmail || dealer.user.email,
        phone: dealer.phone || '',
        address: dealer.address || '',
        city: dealer.city || '',
        state: dealer.state || '',
        zip: dealer.zip || '',
      }}
    />
  );
}
