import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import ThemeSwitcher from '../components/ThemeSwitcher';

const Home = () => {
  const navigate = useNavigate();
  const { user, loginAnonymous, isAuthenticated, updateUserName } = useAuth();
  const [editingName, setEditingName] = useState(false);
  const [nameValue, setNameValue] = useState('');
  const [isUpdating, setIsUpdating] = useState(false);

  useEffect(() => {
    const initAuth = async () => {
      if (!isAuthenticated) {
        try {
          await loginAnonymous('Гость');
        } catch (error) {
          console.error('Auto login failed:', error);
        }
      }
    };

    initAuth();
  }, [isAuthenticated, loginAnonymous]);

  useEffect(() => {
    if (user) {
      setNameValue(user.name || '');
    }
  }, [user]);

  const handleNameClick = () => {
    setEditingName(true);
  };

  const handleNameChange = (e) => {
    setNameValue(e.target.value);
  };

  const handleNameBlur = async () => {
    setEditingName(false);
    
    if (nameValue.trim() && nameValue.trim() !== user?.name) {
      setIsUpdating(true);
      try {
        await updateUserName(nameValue.trim());
      } catch (error) {
        console.error('Failed to update name:', error);
        setNameValue(user?.name || '');
      } finally {
        setIsUpdating(false);
      }
    } else {
      setNameValue(user?.name || '');
    }
  };

  const handleNameKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.target.blur();
    }
  };

  const handleCreateRoom = () => {
    navigate('/create-room');
  };

  const handleJoinRoom = () => {
    navigate('/join-room');
  };

  return (
    <div className="home-page">
      <div className="home-theme-switcher-wrapper">
        <ThemeSwitcher />
      </div>
      <div className="home-container">
        <h1>100 к 1</h1>
        <div className="welcome-text">
          {user ? (
            <>
              Привет,{' '}
              {editingName ? (
                <input
                  type="text"
                  value={nameValue}
                  onChange={handleNameChange}
                  onBlur={handleNameBlur}
                  onKeyPress={handleNameKeyPress}
                  className="name-input-inline"
                  autoFocus
                  maxLength={50}
                  disabled={isUpdating}
                />
              ) : (
                <span 
                  className="name-editable" 
                  onClick={handleNameClick}
                  title="Нажмите, чтобы изменить имя"
                >
                  {user.name}
                </span>
              )}
              !
            </>
          ) : (
            'Добро пожаловать!'
          )}
        </div>

        <div className="menu-buttons">
          <button onClick={handleCreateRoom} className="menu-button primary">
            Создать комнату
          </button>

          <button onClick={handleJoinRoom} className="menu-button">
            Присоединиться к комнате
          </button>
        </div>

        {user && (
          <div className="user-stats">
            <p>Игр сыграно: {user.gamesPlayed || 0}</p>
            <p>Побед: {user.gamesWon || 0}</p>
            <p>Очков: {user.totalPoints || 0}</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Home;
