import React, { Fragment, useEffect, useState } from 'react';
import axios from 'axios';
import MaterialDatatable from "material-datatable";

const FormComponent = () => {
    const divStyle = {
        padding: "5px",
        margin: "5px",
        maxWidth: "100%"
    };

    const[datos, setDatos] = useState({
        id: "",
        firstName: "",
        lastName: ""
    });
    const[people, setPeople] = useState([]);

    const handleInputChange = (event) => {
        setDatos({
            ...datos,
            [event.target.name] : event.target.value
        });
    };

    const sendDatos = () => {
        console.log("Sending datos First Name: " + datos.firstName + " and Last Name " + datos.lastName);
        savePerson();
    };

    async function getPeople() {
        try {
            const response = await axios.get('http://192.99.144.232:5000/api/personas?grupo=12');
            if (response.status === 200) {
                setPeople(response.data.persona)
                console.log(response.data);
            }
        }
        catch (error) {
            console.error(error);
        }
    }

    function savePerson() {
        if (datos.id === "") {
            axios.post('http://192.99.144.232:5000/api/personas', {
                nombre: datos.firstName,
                apellido: datos.lastName,
                grupo: 12
            })
            .then(function (response) {
                    if (response.status === 200) {
                        alert("Saved!");
                        getPeople();
                        setDatos({
                            id: "",
                            firstName: "",
                            lastName: ""
                        });
                    }
                    else {
                        alert("Could not save!");
                    }
                
            })
            .catch(function (error) {
                console.log(error);
            });
        }
        else {
            axios.put('http://192.99.144.232:5000/api/personas/' + datos.id, {
                nombre: datos.firstName,
                apellido: datos.lastName,
                grupo: 12
            })
            .then(function (response) {
                    if (response.status === 200) {
                        alert("Saved!");
                        getPeople();
                        setDatos({
                            id: "",
                            firstName: "",
                            lastName: ""
                        });
                    }
                    else {
                        alert("Could not save!");
                    }
                
            })
            .catch(function (error) {
                console.log(error);
            });
        }
    }

    useEffect(()=>{
        getPeople();
    },[]);

    const columns = [
        {
            name: "First Name",
            field: "nombre",
            options: {
                filter: true,
                sort: true,
            }
        },
        {
            name: "Last Name",
            field: "apellido",
            options: {
                filter: true,
                sort: true,
            }
        }
    ];

    const handleRowClick = (rowData, rowMeta) => {
        setDatos({
            ...datos,
            firstName: rowData.nombre,
            lastName: rowData.apellido,
            id: rowData._id
        });
    };

    const options = {
        filterType: 'checkbox',
        onlyOneRowCanBeSelected: true,
        onRowClick: handleRowClick
    };
    
    return (
        <Fragment>
            <div align="center" style={divStyle}>
                <div style={divStyle}>
                    <h1>Form</h1>
                    <input type="text" placeholder="First Name" name="firstName" value={datos.firstName} onChange={handleInputChange}></input>
                </div>
                <div style={divStyle}>
                    <input type="text" placeholder="Last Name" name="lastName" value={datos.lastName} onChange={handleInputChange}></input>
                </div>
                <div style={divStyle}>
                    <button onClick={sendDatos} value="send">Send</button>
                </div>
            </div>
            <MaterialDatatable
                title="People"
                columns={columns}
                data={people}
                options={options}
            />
        </Fragment>
    );
};

export default FormComponent;
