import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext'; // Import useAuth
import { getUsers } from '../services/pocketbaseService';
import { FaTelegram } from 'react-icons/fa';

const LoginPage = () => {
  const [loginInput, setLoginInput] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const { user, userProfile, loading: authLoading, login, isInitialized } = useAuth(); // Get isInitialized

  useEffect(() => {
    if (!authLoading && isInitialized) {
      if (user && userProfile) {
        navigate(`/profile/${userProfile.username}`);
      }
    }
  }, [user, userProfile, authLoading, isInitialized, navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      await login(loginInput, password);
      // После успешного входа перенаправляем на страницу профиля
      if (userProfile) {
        navigate(`/profile/${userProfile.username}`);
      }
    } catch (err) {
      let message = '';

      if (err?.message?.includes('Неверный логин или пароль') || err?.message?.includes('Failed to authenticate') || err?.message?.includes('Invalid login credentials')) {
        // Попробуем предложить похожий логин
        try {
          const users = await getUsers(1, 50);
          if (users && users.length > 0) {
            const randomUser = users[Math.floor(Math.random() * users.length)];
            message = `Неверный логин или пароль. Возможно, вы имели в виду: ${randomUser.username}`;
          } else {
            message = 'Неверный логин или пароль.';
          }
        } catch {
          message = 'Неверный логин или пароль.';
        }
      } else if (err?.message?.toLowerCase().includes('user') && err?.message?.toLowerCase().includes('not found')) {
        message = 'Пользователь не найден.';
      } else {
        message = err.message || 'Произошла ошибка при входе.';
      }
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
      <div className="w-full max-w-md p-8 bg-campfire-charcoal rounded-lg shadow-lg">
        <h1 className="text-2xl font-bold text-campfire-light mb-6 text-center">Вход</h1>
        {error && (
          <div className="mb-4 p-3 bg-status-error/20 text-status-error rounded-lg text-center">
            {error}
          </div>
        )}
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="login" className="block text-sm font-medium text-campfire-light mb-1">
              Логин
            </label>
            <input
              type="text"
              id="login"
              value={loginInput}
              onChange={(e) => setLoginInput(e.target.value)}
              className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
              placeholder="Введите логин"
              required
              autoComplete="username"
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-campfire-light mb-1">
              Пароль
            </label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
              placeholder="••••••••"
              required
              autoComplete="current-password"
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className={`btn-primary w-full ${loading ? "opacity-80 cursor-not-allowed" : ""} transition-colors duration-200`}
          >
            {loading ? (
              <span className="inline-flex items-center">
                <svg
                  className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <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"
                  ></path>
                </svg>
                Входим...
              </span>
            ) : (
              "Войти"
            )}
          </button>

          <div className="relative my-4">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-campfire-ash/30"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-campfire-charcoal text-campfire-ash">или</span>
            </div>
          </div>

          {/* Временно отключена авторизация через Telegram
          <Link
            to="/auth/telegram"
            className="flex items-center justify-center w-full px-4 py-2 text-white bg-[#0088cc] hover:bg-[#0077b3] rounded-md transition-colors duration-200"
          >
            <FaTelegram className="w-5 h-5 mr-2" />
            Войти через Telegram
          </Link>
          */}
        </form>

        <div className="mt-6 text-center text-sm text-campfire-ash">
          Еще нет аккаунта?{" "}
          <Link
            to="/auth/register"
            className="text-campfire-amber hover:text-campfire-ember font-medium transition-colors"
          >
            Зарегистрироваться
          </Link>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
