import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { loginSchema, type LoginFormData } from './schemas';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { PasswordInput } from '@/features/auth/components/PasswordInput';
import { AuthLayout } from '@/features/auth/components/AuthLayout';
import { AlertCircle } from 'lucide-react';
import { useNavigate, useSearch } from '@tanstack/react-router';
import { authApi } from '@/infrastructure/http/api/auth';
import { tokenStorage } from '@/infrastructure/storage/LocalTokenStorage';
import { authenticatedUserStore } from '@/infrastructure/storage/AuthenticatedUserStore';
import { useTranslation } from '@/i18n/TranslationProvider';
import { WpRegisterPage } from './WpRegisterPage';

/**
 * LoginPage Component
 *
 * Renders the TWWIM-branded login form with:
 * - Email field with validation
 * - Password field with validation
 * - TWWIM branding (primary color #0284c7)
 * - Responsive design (mobile-first)
 *
 * Uses React Hook Form with Zod schema validation.
 */
const isWpEmbed = import.meta.env.VITE_WP_EMBED === 'true';

export function LoginPage() {
  const { t, locale } = useTranslation();
  const landingUrl = import.meta.env.VITE_LANDING_URL || '';
  const navigate = useNavigate();
  const search = useSearch({ from: '/login' }) as { redirect?: string };
  const [showWpRegister, setShowWpRegister] = useState(false);

  // Wipe stale tokens + user snapshot once on mount. MUST NOT run in the
  // component body — react-hook-form re-renders the page after onSubmit
  // resolves (isSubmitting flips back to false) and a body-level clear would
  // race the `_authenticated` guard's in-memory read of authenticatedUserStore,
  // redirecting the user straight back to /login in WP hash-history mode.
  useEffect(() => {
    tokenStorage.removeTokens();
    authenticatedUserStore.clear();
  }, []);

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
  });

  if (isWpEmbed && showWpRegister) {
    return <WpRegisterPage onBack={() => setShowWpRegister(false)} />;
  }

  const onSubmit = async (data: LoginFormData) => {
    try {
      const { user, session, authenticatedUser } = await authApi.login({
        email: data.email,
        password: data.password,
      });

      // Tokens remain in LocalTokenStorage (archer_* keys, legacy).
      // AuthenticatedUser lives in its own twwim_* store. AuthenticatedUserMapper
      // already seeds authOrigin from the JWT inside fromTokenResponse, so we
      // just persist what the API layer returned — no manual JWT merge here.
      tokenStorage.setTokens(session.accessToken, session.refreshToken);
      authenticatedUserStore.set(authenticatedUser);

      console.log('Login successful:', user.email);

      // Navigate to redirect URL or dashboard (never redirect to auth pages)
      const raw = search.redirect || '/dashboard';
      const redirectTo = raw.startsWith('/auth') || raw === '/login' ? '/dashboard' : raw;
      // replace:true — never leave /login in the hash-history back stack so
      // Back/Forward doesn't drop a freshly-authenticated user onto the login
      // page, which would then mount-clear their tokens.
      navigate({ to: redirectTo, replace: true });
    } catch (error) {
      console.error('Login failed:', error);

      // Handle specific error types
      if (error instanceof Error) {
        if (error.message.includes('2FA')) {
          setError('root', { message: t('auth.error2FA') });
        } else if (error.message.includes('Invalid') || error.message.includes('credentials')) {
          setError('root', { message: t('auth.errorInvalidCredentials') });
        } else {
          setError('root', { message: error.message || t('auth.errorLoginFailed') });
        }
      } else {
        setError('root', { message: t('auth.errorUnexpected') });
      }
    }
  };

  return (
    <AuthLayout subtitle={t('auth.signInTitle')}>
      {/* Login Form */}
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {/* Form-level Error Alert (T3.1) */}
            {errors.root && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{errors.root.message}</AlertDescription>
              </Alert>
            )}

            {/* Email Field (T3.5 - Enhanced attributes) */}
            <div>
              <Label htmlFor="email">{t('auth.email')}</Label>
              <Input
                id="email"
                type="email"
                placeholder={t('auth.emailPlaceholder')}
                autoComplete="email"
                autoCapitalize="none"
                autoCorrect="off"
                inputMode="email"
                {...register('email')}
                aria-invalid={errors.email ? 'true' : 'false'}
                aria-describedby={errors.email ? 'email-error' : undefined}
              />
              {errors.email && (
                <p id="email-error" className="mt-1 text-sm text-destructive" role="alert">
                  {errors.email.message}
                </p>
              )}
            </div>

            {/* Password Field (T3.2 - PasswordInput component, T3.3 - Forgot Password link) */}
            <div>
              <div className="flex items-center justify-between">
                <Label htmlFor="password">{t('auth.password')}</Label>
                <a
                  href={`${landingUrl}/${locale}/forgot-password`}
                  className="text-sm text-primary hover:text-primary/80 transition-colors"
                  {...(isWpEmbed ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
                >
                  {t('auth.forgotPassword')}
                </a>
              </div>
              <PasswordInput
                id="password"
                placeholder={t('auth.passwordPlaceholder')}
                autoComplete="current-password"
                {...register('password')}
                error={errors.password?.message}
                aria-invalid={errors.password ? 'true' : 'false'}
                aria-describedby={errors.password ? 'password-error' : undefined}
              />
              {errors.password && (
                <p id="password-error" className="mt-1 text-sm text-destructive" role="alert">
                  {errors.password.message}
                </p>
              )}
            </div>

            {/* Submit Button (T3.4 - Glow effect on hover) */}
            <Button
              type="submit"
              className="w-full transition-all duration-150 hover:shadow-[0_0_20px_rgba(14,165,233,0.3)] active:scale-[0.98]"
              disabled={isSubmitting}
            >
              {isSubmitting ? t('auth.signingIn') : t('auth.signIn')}
            </Button>
          </form>

      {/* Footer with sign-up link */}
      <div className="mt-6 text-center text-sm text-muted-foreground">
        {t('auth.noAccount')}{' '}
        {isWpEmbed ? (
          <button
            type="button"
            onClick={() => setShowWpRegister(true)}
            className="text-primary font-medium hover:underline transition-colors"
          >
            {t('auth.signUp')}
          </button>
        ) : (
          <a
            href={`${landingUrl}/${locale}/register`}
            className="text-primary font-medium hover:underline transition-colors"
          >
            {t('auth.signUp')}
          </a>
        )}
      </div>

    </AuthLayout>
  );
}
