import { Suspense } from 'react';
import Image from 'next/image';
import SignInContent from './SignInContent';
import RegistrationLogoBar from '@/app/registration/components/RegistrationLogoBar';
import '@/app/styles/registration-theme.css';

interface PageProps {
  searchParams: Promise<{
    callbackUrl?: string;
    plan?: string;
    error?: string;
  }>;
}

/**
 * Custom Sign-In Page - AMS_Page2 Design
 *
 * Adaptive split-screen branded sign-in page that serves two flows:
 * 1. Subscription Flow - New dealers subscribing to a plan (when plan parameter exists)
 * 2. Login Flow - Returning dealers accessing their dashboard (no plan parameter)
 *
 * Features:
 * - Split-screen layout (content left, info panel right)
 * - Shows selected plan name with sky blue highlight (subscription flow)
 * - AMSOIL branding
 * - Dark theme matching Figma design
 * - Responsive (stacks vertically on mobile)
 * - Conditional content based on flow type
 * - Maintains all OAuth functionality
 */
export default async function SignInPage({ searchParams }: PageProps) {
  // Extract plan name from URL params or callback URL
  const params = await searchParams;
  const planFromParam = params.plan;
  const callbackUrlParam = params.callbackUrl || '/';

  const planMatch = callbackUrlParam.match(/plan=(\w+)/);
  const planFromCallback = planMatch ? planMatch[1] : null;

  const planName = planFromParam || planFromCallback;

  // Detect flow type based on plan parameter presence
  const isSubscriptionFlow = !!planName;

  const planDisplayNames: Record<string, string> = {
    starter: 'Starter',
    growth: 'Growth',
    enhanced: 'Enhanced',
    professional: 'Professional',
  };

  const displayPlanName = planName ? planDisplayNames[planName.toLowerCase()] || 'Starter' : '';

  // Conditional content based on flow type
  const subtitle = isSubscriptionFlow ? 'Sign in to Continue' : 'Sign in to continue';

  const rightPanelHeading = isSubscriptionFlow ? 'What Happens Next?' : "What's New";

  // Subscription flow checklist
  const subscriptionChecklistItems = [
    'Authenticate with Google OAuth',
    'Complete payment via Stripe',
    'Set up your dealer page',
    'Publish your site and go live!',
  ];

  // Login flow updates list
  const loginUpdateItems = [
    'New dealer information editor features',
    'Enhanced performance dashboard now available',
    'AMSOIL corporate content library updated',
    'Mobile experience improvements',
  ];

  const rightPanelItems = isSubscriptionFlow ? subscriptionChecklistItems : loginUpdateItems;

  // Callback URL for post-authentication redirect
  const callbackUrl = isSubscriptionFlow ? callbackUrlParam : '/dashboard';

  return (
    <div
      className="min-h-screen signin-page-root overflow-visible"
      style={{ backgroundColor: 'var(--reg-bg-navy)' }}
    >
      {/* Logo Bar - Shared Component */}
      <RegistrationLogoBar />

      {/* Two-Column Layout - natural height, columns stretch to match */}
      <div className="flex flex-col lg:flex-row signin-two-column-layout relative lg:min-h-[calc(100vh-80px)]">
        {/* 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 Panel - Sign In Content */}
        <div className="w-full lg:w-1/2 flex items-start justify-center p-8 lg:py-12 lg:px-12 signin-left-column">
          <div className="w-full max-w-md signin-content-wrapper py-4">
            {/* Sign In Content - Wrapped in Suspense for client component */}
            <Suspense
              fallback={
                <div className="space-y-8">
                  <div className="space-y-4">
                    <div className="h-16 bg-white/10 rounded-lg animate-pulse"></div>
                    <div className="h-8 bg-white/10 rounded-lg animate-pulse w-2/3"></div>
                  </div>
                  <div className="space-y-4">
                    <div className="h-14 bg-white/10 rounded-lg animate-pulse"></div>
                    <div className="h-14 bg-white/10 rounded-lg animate-pulse"></div>
                  </div>
                </div>
              }
            >
              <SignInContent
                callbackUrl={callbackUrl}
                subtitle={subtitle}
                isSubscriptionFlow={isSubscriptionFlow}
                displayPlanName={displayPlanName}
              />
            </Suspense>
          </div>
        </div>

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

            {/* Checklist / Updates */}
            <div className="space-y-6 signin-checklist">
              {rightPanelItems.map((item, index) => (
                <div key={index} className="flex items-start gap-4 signin-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)' }}
                  >
                    {item}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
