'use client';

import { signIn } from 'next-auth/react';
import Image from 'next/image';
import { useSearchParams } from 'next/navigation';
import EmailAuthForm from './EmailAuthForm';
import OrDivider from './OrDivider';

interface SignInContentProps {
  callbackUrl?: string;
  subtitle?: string;
  isSubscriptionFlow?: boolean;
  displayPlanName?: string;
}

/**
 * Client Component for Sign-In Content
 *
 * Displays a unified sign-in experience with:
 * - OAuth buttons (Google, Apple) at the top
 * - OR divider
 * - Email authentication form (sign-in or sign-up mode)
 * - Terms disclaimer at the bottom
 *
 * The email form defaults to sign-up mode for subscription flows,
 * sign-in mode otherwise.
 */
export default function SignInContent({
  callbackUrl,
  subtitle,
  isSubscriptionFlow,
  displayPlanName,
}: SignInContentProps) {
  const searchParams = useSearchParams();
  const error = searchParams.get('error');

  // Default email form mode based on flow type
  const defaultEmailMode = isSubscriptionFlow ? 'signup' : 'signin';

  const handleGoogleSignIn = async () => {
    await signIn('google', {
      callbackUrl: callbackUrl || '/dashboard',
    });
  };

  const handleAppleSignIn = async () => {
    await signIn('apple', {
      callbackUrl: callbackUrl || '/dashboard',
    });
  };

  // Heading content based on subscription flow
  const getHeadingContent = () => {
    if (isSubscriptionFlow) {
      return (
        <>
          Subscribe
          <br />
          to the{' '}
          <span className="signin-plan-name-highlight" style={{ color: 'var(--reg-accent-sky)' }}>
            {displayPlanName} Plan
          </span>
        </>
      );
    }
    return (
      <>
        Access Your
        <br />
        Dashboard
      </>
    );
  };

  return (
    <div className="space-y-5">
      {/* Heading */}
      <div className="space-y-2 signin-heading-section">
        <h1
          className="text-[40px] lg:text-[65px] font-bold leading-[0.94] signin-main-heading"
          style={{ color: 'var(--reg-text-white)', letterSpacing: '-0.02em' }}
        >
          {getHeadingContent()}
        </h1>
        <p
          className="text-[24px] lg:text-[28px] font-normal leading-[1.25] signin-subtitle"
          style={{ color: 'var(--reg-text-white)', letterSpacing: '-0.02em' }}
        >
          {subtitle}
        </p>
      </div>

      {/* Unified Authentication Options */}
      <div className="space-y-3">
        {/* Error Message */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
            <p className="text-red-400 text-sm">
              {error === 'OAuthAccountNotLinked'
                ? 'This email is already associated with another sign-in method. Please use the same method you used previously.'
                : error === 'CredentialsSignin'
                  ? 'Invalid email or password. Please try again.'
                  : 'An error occurred during sign in. Please try again.'}
            </p>
          </div>
        )}

        {/* Google Sign In Button */}
        <button
          onClick={handleGoogleSignIn}
          className="w-full h-11 bg-white hover:bg-gray-50 transition-colors rounded-lg flex items-center justify-center gap-3 group shadow-sm border border-gray-200 signin-oauth-button signin-google-button"
          type="button"
          aria-label="Sign in with Google"
        >
          <Image
            src="/media/icons/google-icon.svg"
            alt=""
            width={20}
            height={20}
            className="w-5 h-5"
          />
          <span className="text-gray-700 font-medium">Sign in with Google</span>
        </button>

        {/* Apple Sign In Button */}
        <button
          onClick={handleAppleSignIn}
          className="w-full h-11 bg-white hover:bg-gray-50 transition-colors rounded-lg flex items-center justify-center gap-3 group shadow-sm border border-gray-200 signin-oauth-button signin-apple-button"
          type="button"
          aria-label="Sign in with Apple"
        >
          <Image
            src="/media/icons/apple-button.svg"
            alt=""
            width={20}
            height={20}
            className="w-5 h-5"
          />
          <span className="text-gray-700 font-medium">Sign in with Apple</span>
        </button>

        {/* OR Divider */}
        <OrDivider />

        {/* Email Authentication Form */}
        <EmailAuthForm defaultMode={defaultEmailMode} callbackUrl={callbackUrl || '/dashboard'} />

        {/* Disclaimer */}
        <p
          className="text-[13px] italic leading-[1.3] signin-disclaimer"
          style={{ color: 'var(--reg-text-muted)', letterSpacing: '-0.03em' }}
        >
          By signing in, you agree to our terms of service and privacy policy.
        </p>
      </div>
    </div>
  );
}
