'use client';

import { useState, Suspense } from 'react';
import { useRouter, 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 toast from 'react-hot-toast';

function LoginContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t, locale: language } = useLanguage();
  const { login } = useAuth();
  const [loading, setLoading] = 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
  const redirectTo = searchParams.get('redirect') || '/dashboard';

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

    try {
      await login(formData.email, formData.password);
      toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome back!');
      router.push(redirectTo);
    } catch (error: any) {
      toast.error(error.message || t('auth.errors.invalidCredentials'));
    } finally {
      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);
    }
  };

  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}>
                    {t('auth.login.submit')}
                  </Button>
                </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>
  );
}
