'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { useLanguage } from '@/context/LanguageContext';
import { useAuth } from '@/context/AuthContext';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import GoogleSignInButton from '@/components/GoogleSignInButton';
import { authApi } from '@/lib/api';
import { safeInternalPath } from '@/lib/safeRedirect';
import {
  clearRedirectAttempt,
  didRedirectBounce,
  redirectAfterAuth,
} from '@/lib/authRedirect';
import toast from 'react-hot-toast';

function LoginContent() {
  const searchParams = useSearchParams();
  const { t, locale: language } = useLanguage();
  const { login, user, isLoading: authLoading } = useAuth();
  const [loading, setLoading] = useState(false);
  const [redirecting, setRedirecting] = useState(false);
  const [bounced, setBounced] = useState(false);
  const [loginMode, setLoginMode] = useState<'password' | 'magic-link'>('password');
  const [magicLinkSent, setMagicLinkSent] = useState(false);
  const [formData, setFormData] = useState({
    email: '',
    password: '',
  });

  // Check for redirect after login (only same-origin relative paths are honoured)
  const redirectTo = safeInternalPath(searchParams.get('redirect'), '/dashboard');

  // Send an already-signed-in visitor on to their destination — and detect the case
  // where that destination bounced them back here, which otherwise looks like the
  // login page silently ignoring a successful sign-in.
  useEffect(() => {
    if (authLoading || redirecting) return;

    if (!user) {
      // Signed out on the login page is a clean slate.
      clearRedirectAttempt();
      return;
    }

    if (didRedirectBounce(redirectTo)) {
      setBounced(true);
      return;
    }

    setRedirecting(true);
    redirectAfterAuth(redirectTo);
  }, [authLoading, redirecting, user, redirectTo]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      await login(formData.email, formData.password);
      toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome back!');
      // Deliberately leaves `loading` set: the button must stay disabled until the
      // browser replaces this page.
      setRedirecting(true);
      redirectAfterAuth(redirectTo);
    } catch (error: any) {
      toast.error(error.message || t('auth.errors.invalidCredentials'));
      setLoading(false);
    }
  };

  const handleMagicLinkRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.email) {
      toast.error(language === 'es' ? 'Ingresa tu email' : 'Please enter your email');
      return;
    }

    setLoading(true);
    try {
      await authApi.requestMagicLink(formData.email);
      setMagicLinkSent(true);
      toast.success(
        language === 'es'
          ? 'Revisa tu correo para el enlace de acceso'
          : 'Check your email for the login link'
      );
    } catch (error: any) {
      toast.error(error.message || (language === 'es' ? 'Error' : 'Failed'));
    } finally {
      setLoading(false);
    }
  };

  // The destination sent us back here even though the session is valid. Say so, rather
  // than re-showing a form that appears to do nothing. The retry link is a plain <a> so
  // it is a full page load, like every other navigation out of this page.
  if (bounced) {
    return (
      <div className="section-padding min-h-[70vh] flex items-center">
        <div className="container-page">
          <div className="max-w-md mx-auto">
            <Card className="p-8 text-center">
              <h1 className="text-2xl font-bold">{t('auth.login.redirectBlocked')}</h1>
              {user && <p className="mt-2 text-sm text-gray-600">{user.email}</p>}
              <p className="mt-4 text-sm text-gray-600">
                <code className="px-1.5 py-0.5 bg-gray-100 rounded">{redirectTo}</code>
              </p>
              <a href={redirectTo} className="mt-6 block">
                <Button className="w-full" size="lg">
                  {t('auth.login.redirectRetry')}
                </Button>
              </a>
              <Link
                href="/"
                className="mt-3 inline-block text-sm text-secondary-blue hover:underline"
              >
                {t('nav.home')}
              </Link>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="section-padding min-h-[70vh] flex items-center">
        <div className="container-page">
          <div className="max-w-md mx-auto">
            <div className="text-center mb-8">
              <h1 className="text-3xl font-bold">{t('auth.login.title')}</h1>
              <p className="mt-2 text-gray-600">{t('auth.login.subtitle')}</p>
            </div>

            <Card className="p-8">
              {/* Google Sign-In Button */}
              <GoogleSignInButton 
                redirectTo={redirectTo}
                text="continue_with"
                className="mb-4"
              />
              
              {/* Or Divider */}
              <div className="relative my-6">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-gray-300"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="px-2 bg-white text-gray-500">
                    {language === 'es' ? 'o continuar con' : 'or continue with'}
                  </span>
                </div>
              </div>

              {/* Login Mode Tabs */}
              <div className="flex gap-2 mb-6">
                <button
                  type="button"
                  onClick={() => setLoginMode('password')}
                  className={`flex-1 py-2 px-4 text-sm font-medium rounded-lg transition-colors ${
                    loginMode === 'password'
                      ? 'bg-secondary-blue text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  {language === 'es' ? 'Contraseña' : 'Password'}
                </button>
                <button
                  type="button"
                  onClick={() => setLoginMode('magic-link')}
                  className={`flex-1 py-2 px-4 text-sm font-medium rounded-lg transition-colors ${
                    loginMode === 'magic-link'
                      ? 'bg-secondary-blue text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  {language === 'es' ? 'Enlace por Email' : 'Email Link'}
                </button>
              </div>

              {loginMode === 'password' ? (
                <form onSubmit={handleSubmit} className="space-y-6">
                  <Input
                    id="email"
                    label={t('auth.login.email')}
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    required
                  />
                  
                  <Input
                    id="password"
                    label={t('auth.login.password')}
                    type="password"
                    value={formData.password}
                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    required
                  />
                  
                  <div className="flex justify-end">
                    <Link
                      href="/auth/forgot-password"
                      className="text-sm text-secondary-blue hover:underline"
                    >
                      {language === 'es' ? '¿Olvidaste tu contraseña?' : 'Forgot password?'}
                    </Link>
                  </div>
                  
                  <Button
                    type="submit"
                    className="w-full"
                    size="lg"
                    isLoading={loading || redirecting}
                    loadingText={redirecting ? t('auth.login.redirecting') : t('common.loading')}
                  >
                    {t('auth.login.submit')}
                  </Button>

                  {redirecting && (
                    <p
                      className="text-center text-sm text-gray-600"
                      role="status"
                      aria-live="polite"
                    >
                      {t('auth.login.redirecting')}
                    </p>
                  )}
                </form>
              ) : magicLinkSent ? (
                <div className="text-center py-8">
                  <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <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>
                  <h3 className="text-lg font-semibold mb-2">
                    {language === 'es' ? 'Revisa tu Email' : 'Check Your Email'}
                  </h3>
                  <p className="text-gray-600 text-sm mb-4">
                    {language === 'es'
                      ? `Enviamos un enlace de acceso a ${formData.email}`
                      : `We sent a login link to ${formData.email}`}
                  </p>
                  <button
                    onClick={() => setMagicLinkSent(false)}
                    className="text-secondary-blue hover:underline text-sm"
                  >
                    {language === 'es' ? 'Usar otro email' : 'Use a different email'}
                  </button>
                </div>
              ) : (
                <form onSubmit={handleMagicLinkRequest} className="space-y-6">
                  <Input
                    id="magic-email"
                    label={t('auth.login.email')}
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    required
                  />
                  <p className="text-sm text-gray-500 -mt-4">
                    {language === 'es'
                      ? 'Te enviaremos un enlace para iniciar sesión sin contraseña'
                      : "We'll send you a link to sign in without a password"}
                  </p>
                  
                  <Button type="submit" className="w-full" size="lg" isLoading={loading}>
                    {language === 'es' ? 'Enviar Enlace' : 'Send Login Link'}
                  </Button>
                </form>
              )}

              <p className="mt-6 text-center text-sm text-gray-600">
                {t('auth.login.noAccount')}{' '}
                <Link href="/register" className="text-secondary-blue hover:underline font-medium">
                  {t('auth.login.register')}
                </Link>
              </p>
            </Card>
          </div>
        </div>
      </div>
  );
}

function LoadingFallback() {
  return (
    <div className="section-padding min-h-[70vh] flex items-center justify-center">
      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-secondary-blue"></div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={<LoadingFallback />}>
      <LoginContent />
    </Suspense>
  );
}
