import './css/loginform.css';
import React, { useState, useEffect } from 'react';
import { Modal, Form, Button, } from 'react-bootstrap';
import axios from 'axios';

const CreateTeam = ({ showCreateTeamForm, setShowCreateTeamForm, setAlertType, setAlertMessage, setShowAlert }) => {

    const [championships, setChampionships] = useState(null);

    const handleClose = () => {
        setTeamData(() => ({
            name: "",
            ground: "",
            championships: 1
        }));
        setShowCreateTeamForm(false);
    };

    const handleShow = () => setShowCreateTeamForm(true);

    const [teamData, setTeamData] = useState({
        name: "",
        ground: "",
        championships: 1
    });

    const handleNameInputChange = (e) => {
        setTeamData((values) => ({
            ...values,
            name: e.target.value
        }));
    };

    const handleGroundInputChange = (e) => {
        setTeamData((values) => ({
            ...values,
            ground: e.target.value
        }));
    };

    const handleChampionshipInputChange = (e) => {
        setTeamData((values) => ({
            ...values,
            championships: e.target.value
        }));
    };

    const getChampionships = () => {
        axios.get('http://localhost:8080/pa165/championships',
            {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            })
            .then(function (response) {
                // handle success
                setChampionships(response.data.content);
            })
            .catch(function (error) {
                setAlertType(1);
                setAlertMessage("Coulnd load data");
                setShowAlert(true);
            });
    }

    const createTeam = () => {
        const json = JSON.stringify({
            name: teamData.name,
            ground: teamData.name,
        });

        axios.post('http://localhost:8080/pa165/leagues/' + 2 + '/teams', json,
            {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            })
            .then(function (response) {
                // handle success
                console.log(response);
                setChampionships(response.data.content);
            })
            .catch(function (error) {
                setAlertType(1);
                setAlertMessage("Coulnd load data");
                setShowAlert(true);
            });
    }

    const handleCreate = () => {
        if (teamData.name === "") {
            setAlertType(1);
            setAlertMessage("Name is required!")
            setShowAlert(true);

        }
        else if (teamData.ground === "") {
            setAlertType(1);
            setAlertMessage("Ground is required!")
            setShowAlert(true);
        }
        else {
            createTeam();
            handleClose();
        }
    };

    useEffect(() => {
        if (championships === null) {
            getChampionships();
        }
    }, []);

    return (
        <>
            <Modal show={showCreateTeamForm} onHide={handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>New team</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Form>
                        <Form.Group className="mb-3" controlId="Team.Name">
                            <Form.Label>Team name</Form.Label>
                            <Form.Control
                                type="text"
                                placeholder="Team name"
                                value={teamData.name}
                                onChange={handleNameInputChange}
                                autoFocus
                            />
                        </Form.Group>
                        <Form.Group className="mb-3" controlId="Team.Name">
                            <Form.Label>Ground</Form.Label>
                            <Form.Control
                                type="text"
                                placeholder="Ground name"
                                value={teamData.ground}
                                onChange={handleGroundInputChange}
                                autoFocus
                            />
                        </Form.Group>
                        <Form.Group className="mb-3" controlId="Team.StartDate">
                            <Form.Label>Championship</Form.Label>
                            <Form.Select onChange={handleChampionshipInputChange} defaultValue={null}>
                                <option key={"null"} value={"null"} disabled>No championship</option>
                                {
                                    championships != null ?
                                        championships.map((championship) => {
                                            return (
                                                <option key={championship.id} value={championship.id}>{championship.name} ({championship.country})</option>
                                            );
                                        })
                                        :
                                        <></>
                                }
                            </Form.Select>
                        </Form.Group>
                    </Form>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleClose}>
                        Close
                    </Button>
                    <Button variant="primary" onClick={handleCreate}>
                        Create
                    </Button>
                </Modal.Footer>
            </Modal>
        </>
    );
}

export default CreateTeam;