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

const ModifyTeam = ({ showModifyTeamForm, setShowModifyTeamForm, setAlertType, setAlertMessage, setShowAlert, team = null, setTeam, setData }) => {

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

    const handleClose = () => {
        setShowModifyTeamForm(false);
    };

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

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

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

    const handleChampionshipInputChange = (e) => {
        console.log(e.target.value);
        setTeam((values) => ({
            ...values,
            championship: 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 ModifyTeam = () => {
        const json = JSON.stringify({
            id: team.id,
            name: team.name,
            ground: team.ground,
            league: team.league,
            championship: typeof team.championship === 'object' && team.championship !== null ? team.championship.id : team.championship
        });

        axios.put('http://localhost:8080/pa165/teams/' + team.id, json, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        })
            .then(function (response) { })
            .catch(function (error) {
                // handle error
                setAlertType(1);
                setAlertMessage("Coulnd update team.");
                setShowAlert(true);
            });
    }

    const handleUpdate = () => {
        if (team.name === "") {
            setAlertType(1);
            setAlertMessage("Name is required!")
            setShowAlert(true);
        }
        else if (team.ground === "") {
            setAlertType(1);
            setAlertMessage("Ground is required!")
            setShowAlert(true);
        }
        else {
            ModifyTeam();
            setData(null);
            handleClose();
        }
    };

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

    if (team != null) {
        return (
            <>
                <Modal show={showModifyTeamForm} onHide={handleClose}>
                    <Modal.Header closeButton>
                        <Modal.Title>Modify 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={team.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={team.ground}
                                    onChange={handleGroundInputChange}
                                />
                            </Form.Group>
                            <Form.Group className="mb-3" controlId="Team.StartDate">
                                <Form.Label>Championship</Form.Label>
                                <Form.Select onChange={handleChampionshipInputChange} defaultValue={team.championship === null ? "null" : team.championship.id}>
                                    <option key={"null"} value={"null"}>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={handleUpdate}>
                            Update
                        </Button>
                    </Modal.Footer>
                </Modal>
            </>
        );
    }
}

export default ModifyTeam;