import React, { useContext, useEffect, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import axios from 'axios';
import { UserContext} from '../context/UserContext';
import './home.css';

function Home({ isLoggedIn, setIsLoggedIn }) {
    const navigate = useNavigate();
    const [games, setGames] = useState([]);
    const { userId } = useContext(UserContext);

    useEffect(() => {
        if (isLoggedIn && userId) {
            axios.get(`http://localhost:5000/games/${userId}`)
                .then(response => {
                    setGames(response.data);
                })
                .catch(error => {
                    console.error('Error fetching games:', error);
                });
        }
    }, [isLoggedIn, userId]);

    const handleLogout = () => {
        setIsLoggedIn(false);
    };

    return (
        <div className="container">
            <h2>Welcome to P&P-Master</h2>
            {!isLoggedIn ? (
                <div className="button-group">
                    <button className="btn" onClick={() => navigate('/login')}>Login</button>
                    <button className="btn" onClick={() => navigate('/register')}>Register</button>
                </div>
            ) : (
                <div className="content">
                    <div className="button-group">
                        <button className="btn" onClick={() => navigate('/startGame')}>Start Game</button>
                        <button className="btn" onClick={() => navigate('/joinGame')}>Join Game</button>
                        <button className="btn" onClick={handleLogout}>Logout</button>
                    </div>
                    <div className="table-container">
                        <h3>Your Games</h3>
                        <table className="games-table">
                            <thead>
                                <tr>
                                    <th>Game ID</th>
                                    <th>Name</th>
                                    <th>Description</th>
                                </tr>
                            </thead>
                            <tbody>
                                {games.map(game => (
                                    <tr key={game.game_id}>
                                        <td>
                                            <Link to={`/games/${game.game_id}`} className="game-link">
                                                {game.game_id}
                                            </Link>
                                        </td>
                                        <td>{game.name}</td>
                                        <td>{game.description}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
        </div>
    );
}

export default Home;