import React, { useState, useEffect } from 'react';
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';
import Alert from './components/Alert';
import MatchesTable from './components/MatchesTable';
import LoginForm from './components/LoginForm';
import RegisterForm from './components/RegisterForm';

import { useParams } from 'react-router-dom';
import axios from 'axios';

const Matches = () => {
    const [logged, setLogged] = useState(false);
    const [showLoginForm, setShowLoginForm] = useState(false);
    const [showRegisterForm, setShowRegisterForm] = useState(false);
    let { leagueId } = useParams();

    const [showAlert, setShowAlert] = useState(false);
    const [alertType, setAlertType] = useState(0);
    const [alertMessage, setAlertMessage] = useState("");
    const [data, setData] = useState(null);

    const getMatches = () => {
        axios.get('http://localhost:8080/pa165/leagues/' + leagueId + '/matches',
            {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            })
            .then(function (response) {
                setData(response.data);
            })
            .catch(function (error) {
                setAlertType(1);
                setAlertMessage("Coulnd load data");
                setShowAlert(true);
            });
    }

    useEffect(() => {
        if (logged) {
            if (data === null) {
                getMatches();
            }
        } else {
            setData(null);
        }
    }, [logged, data]);

    return (
        <div className="myteam">
            <Alert showAlert={showAlert} alertType={alertType} alertMessage={alertMessage} setShowAlert={setShowAlert} setAlertType={setAlertType} setAlertMessage={setAlertMessage} />
            <Header logged={logged} setLogged={setLogged} setShowLoginForm={setShowLoginForm} setShowRegisterForm={setShowRegisterForm} />
            <main className="container-fluid main">
                <LoginForm showLoginForm={showLoginForm} setShowLoginForm={setShowLoginForm} setLogged={setLogged} setShowRegisterForm={setShowRegisterForm} setAlertType={setAlertType} setAlertMessage={setAlertMessage} setShowAlert={setShowAlert} />
                <RegisterForm showRegisterForm={showRegisterForm} setShowRegisterForm={setShowRegisterForm} setShowLoginForm={setShowLoginForm} setAlertType={setAlertType} setAlertMessage={setAlertMessage} setShowAlert={setShowAlert} />
                <section className="container-xxl">
                    <MatchesTable data={data} />
                </section>
            </main>
            <Footer />
        </div>
    );
}

export default Matches;
