/**
 * @ai-summary Mobile "Check Your Email" screen - handles both pre-verification and post-verification states
 * @ai-context No authentication required - auto-triggers login when verification success is detected
 */

import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
import { MobileContainer } from '../../../shared-minimal/components/mobile/MobileContainer';
import { GlassCard } from '../../../shared-minimal/components/mobile/GlassCard';
import { Button } from '../../../shared-minimal/components/Button';
import { useResendVerificationPublic } from '../hooks/useVerifyStatus';

export const VerifyEmailMobileScreen: React.FC = () => {
  const location = useLocation();
  const { loginWithRedirect, isAuthenticated, isLoading: isAuthLoading } = useAuth0();
  const { mutate: resendVerification, isPending: isResending } = useResendVerificationPublic();

  // Track if auto-login is in progress
  const [isAutoLoginTriggered, setIsAutoLoginTriggered] = useState(false);

  // Get email from navigation state (passed from signup page) or localStorage
  // localStorage is used when Auth0 redirects after verification (state is lost)
  const stateEmail = (location.state as { email?: string })?.email || '';
  const storedEmail = localStorage.getItem('pendingVerificationEmail') || '';
  const email = stateEmail || storedEmail;

  // Parse URL search params for verification success detection
  // Auth0 redirects with ?message=Your%20email%20was%20verified... on success
  const searchParams = new URLSearchParams(location.search);
  const message = searchParams.get('message');
  const verificationSuccessful = message && message.toLowerCase().includes('verified');

  // Auto-login effect: triggers when verification success is detected
  useEffect(() => {
    if (isAuthLoading) return;
    if (isAuthenticated) return;

    if (verificationSuccessful && !isAutoLoginTriggered) {
      setIsAutoLoginTriggered(true);
      console.log('[VerifyEmailMobileScreen] Verification success detected, triggering auto-login with email:', email);

      // Clear the stored email after successful verification
      localStorage.removeItem('pendingVerificationEmail');

      // Redirect to Auth0 login with email pre-filled
      loginWithRedirect({
        appState: { returnTo: '/callback' },
        authorizationParams: {
          login_hint: email || undefined,
        },
      });
    }
  }, [verificationSuccessful, isAuthenticated, isAuthLoading, isAutoLoginTriggered, loginWithRedirect, email]);

  const handleResend = () => {
    if (email) {
      resendVerification(email);
    }
  };

  const handleBackToLogin = () => {
    loginWithRedirect();
  };

  // Show loading state when auto-login is in progress
  if (isAutoLoginTriggered || (verificationSuccessful && !isAuthLoading)) {
    return (
      <MobileContainer>
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center px-4">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 mb-4">
              <svg
                className="w-8 h-8 text-green-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
            <h2 className="text-xl font-semibold text-slate-800 mb-2">
              Email Verified!
            </h2>
            <p className="text-slate-600 mb-4">Logging you in automatically...</p>
            <div className="inline-flex items-center justify-center w-8 h-8">
              <svg
                className="w-8 h-8 text-primary-600 animate-spin"
                fill="none"
                viewBox="0 0 24 24"
              >
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
            </div>
          </div>
        </div>
      </MobileContainer>
    );
  }

  return (
    <MobileContainer>
      <div className="flex-1 overflow-y-auto p-4 space-y-6">
        <div className="text-center pt-8 pb-4">
          <div className="mx-auto w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center mb-4">
            <svg
              className="w-8 h-8 text-primary-600"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
              />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-slate-800 mb-2">Check Your Email</h1>
          <p className="text-slate-600">
            We've sent a verification link to
          </p>
          {email && (
            <p className="text-primary-600 font-medium mt-1 break-words px-4">
              {email}
            </p>
          )}
        </div>

        <GlassCard>
          <div className="space-y-4">
            <div className="bg-slate-50 rounded-lg p-4 text-sm text-slate-700">
              <p className="mb-2">Click the link in the email to verify your account.</p>
              <p>Once verified, you can log in to complete your profile setup.</p>
            </div>

            <div className="space-y-3">
              <Button
                onClick={handleBackToLogin}
                variant="primary"
                className="w-full min-h-[44px]"
              >
                Back to Login
              </Button>

              {email && (
                <div className="text-center">
                  <p className="text-sm text-slate-600 mb-2">Didn't receive the email?</p>
                  <Button
                    onClick={handleResend}
                    loading={isResending}
                    variant="secondary"
                    className="w-full min-h-[44px]"
                  >
                    Resend Verification Email
                  </Button>
                </div>
              )}
            </div>
          </div>
        </GlassCard>

        <div className="text-center text-sm text-slate-500 pb-8 px-4">
          <p>Check your spam folder if you don't see the email in your inbox.</p>
        </div>
      </div>
    </MobileContainer>
  );
};

export default VerifyEmailMobileScreen;
