import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Eye, EyeOff, Loader2 } from 'lucide-react';
import { SocialLoginButtons } from '../components/SocialLoginButtons';
import { PhoneLoginForm } from '../components/PhoneLoginForm';

type LoginMethod = 'email' | 'phone';

export default function Login() {
  const navigate = useNavigate();
  const [loginMethod, setLoginMethod] = useState<LoginMethod>('email');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    email: '',
    password: '',
    rememberMe: false,
    totpCode: '',
  });

  const [requiresTwoFactor, setRequiresTwoFactor] = useState(false);

  const handleEmailLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: formData.email,
          password: formData.password,
          totpCode: formData.totpCode || undefined,
          rememberMe: formData.rememberMe,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Error al iniciar sesion');
      }

      if (data.requiresTwoFactor) {
        setRequiresTwoFactor(true);
        return;
      }

      // Store tokens
      localStorage.setItem('accessToken', data.data.tokens.accessToken);
      localStorage.setItem('refreshToken', data.data.tokens.refreshToken);

      // Redirect to dashboard
      navigate('/dashboard');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error desconocido');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <h2 className="text-2xl font-bold text-white mb-2">Iniciar Sesion</h2>
      <p className="text-gray-400 mb-6">
        Accede a tu cuenta de OrbiQuant
      </p>

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-red-900/30 border border-red-800 text-red-400 text-sm">
          {error}
        </div>
      )}

      {/* Social Login Buttons */}
      <SocialLoginButtons />

      <div className="relative my-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-700"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-4 bg-gray-900 text-gray-400">o continua con</span>
        </div>
      </div>

      {/* Login Method Tabs */}
      <div className="flex gap-2 mb-6">
        <button
          type="button"
          onClick={() => setLoginMethod('email')}
          className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium transition-colors ${
            loginMethod === 'email'
              ? 'bg-primary-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          Email
        </button>
        <button
          type="button"
          onClick={() => setLoginMethod('phone')}
          className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium transition-colors ${
            loginMethod === 'phone'
              ? 'bg-primary-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          Telefono
        </button>
      </div>

      {loginMethod === 'email' ? (
        <form onSubmit={handleEmailLogin} className="space-y-4">
          {!requiresTwoFactor ? (
            <>
              <div>
                <label className="label">Email</label>
                <input
                  type="email"
                  className="input"
                  placeholder="tu@email.com"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  required
                />
              </div>

              <div>
                <label className="label">Contrasena</label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    className="input pr-10"
                    placeholder="********"
                    value={formData.password}
                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
                  >
                    {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
                  <input
                    type="checkbox"
                    className="rounded border-gray-600 bg-gray-700"
                    checked={formData.rememberMe}
                    onChange={(e) => setFormData({ ...formData, rememberMe: e.target.checked })}
                  />
                  Recordarme
                </label>
                <Link to="/forgot-password" className="text-sm text-primary-400 hover:underline">
                  Olvidaste tu contrasena?
                </Link>
              </div>
            </>
          ) : (
            <div>
              <label className="label">Codigo de verificacion (2FA)</label>
              <input
                type="text"
                className="input text-center text-2xl tracking-widest"
                placeholder="000000"
                maxLength={6}
                value={formData.totpCode}
                onChange={(e) => setFormData({ ...formData, totpCode: e.target.value.replace(/\D/g, '') })}
                autoFocus
                required
              />
              <p className="text-sm text-gray-400 mt-2">
                Ingresa el codigo de tu app de autenticacion
              </p>
            </div>
          )}

          <button
            type="submit"
            disabled={isLoading}
            className="btn btn-primary w-full flex items-center justify-center gap-2"
          >
            {isLoading ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                Iniciando sesion...
              </>
            ) : requiresTwoFactor ? (
              'Verificar'
            ) : (
              'Iniciar Sesion'
            )}
          </button>

          {requiresTwoFactor && (
            <button
              type="button"
              onClick={() => {
                setRequiresTwoFactor(false);
                setFormData({ ...formData, totpCode: '' });
              }}
              className="w-full text-sm text-gray-400 hover:text-white"
            >
              Volver
            </button>
          )}
        </form>
      ) : (
        <PhoneLoginForm />
      )}

      <div className="mt-6 text-center text-sm text-gray-400">
        No tienes cuenta?{' '}
        <Link to="/register" className="text-primary-400 hover:underline">
          Registrate
        </Link>
      </div>
    </div>
  );
}
