import { Component } from "react";
import Router from 'next/router'

export class Player extends Component {

    constructor(props) {
        super(props);
        this.state = {
            players: [],
            playerCount: 0,
            name: "",
            isTeam: true,
            team: null
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }

    componentDidMount() {
        const url = "https://localhost:1235/players";
        fetch(url)
            .then(response => response.json())
            .then(json => this.setState({ players: json }))
    }

    handleChange(event) {
        this.setState({ name: event.target.name });
    }

    handleSubmit(event) {
        // update name player
        this.isAllPlayerReady(event)
    }

    handleClick(event) {
        //send remove player
        this.isAllPlayerReady(event)
    }

    isAllPlayerReady(event) {
        this.setState({ name: "" })
        if (this.state.players.length < this.state.playerCount) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            // launch the game
            Router.push('/game')
        }
    }



    render() {
        return (
            <div className="p-5 my-5 bg-light border-bottom text-center">
                <h1 className="display-5 fw-bold">{this.state.players[this.state.playerCount]}</h1>
                <div className="col-lg-6 mx-auto">
                    <form className="row g-3" onSubmit={this.handleSubmit}>
                        <div className="form-floating mb-3">
                            <input type="text" className="form-control" id="name" placeholder="Username" value={this.state.name} onChange={this.handleChange} required/>
                            <label  for="name">Pseudo</label>
                        </div>
                        <div className="mb-3">
                            <select name="team" class="form-select" aria-label="Default select example" disabled={!this.state.isTeam} required>
                                <option selected>Choix de l'equipe</option>
                                <option value="A">A</option>
                                <option value="B">B</option>
                            </select>
                        </div>
                        <div className="d-grid gap-2 d-sm-flex justify-content-sm-center">
                            <button type="submit" className="btn btn-primary btn-lg px-4 gap-3">Valider</button>
                            <button type="button" className="btn btn-outline-secondary btn-lg px-4" onClick={this.handleClick}>Ne participe pas</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}