import React, { Fragment, useEffect, useState, forwardRef } from 'react';
import axios from 'axios';
import MaterialTable from "material-table";
import AddBox from '@material-ui/icons/AddBox';
import ArrowDownward from '@material-ui/icons/ArrowDownward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
  };

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

    const[datos, setDatos] = useState("");
    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() {
        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({
                        firstName: "",
                        lastName: ""
                    });
                }
                else {
                    alert("Could not save!");
                }
            
        })
        .catch(function (error) {
            console.log(error);
        });
    }

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

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

    const handleRowClick = (rowData, rowMeta) => {
        console.log(rowData.name)
    };

    const options = {
        exportButton: true,
        selection: true,
        onlyOneRowCanBeSelected: true,
        onRowClick: handleRowClick
    };

    const actions = [
        {
            icon: 'edit',
            tooltip: 'Edit Index',
            onClick: (event, rowData) => {
                this.onEditClick(null, rowData._id);
            }
        },
        {
            icon: 'delete',
            tooltip: 'Delete Index',
            onClick: (event, rowData) => {
                this.onDeleteClick(null, rowData._id);
            }
        },
    ];
    
    return (
        <Fragment>
            <div align="center" style={divStyle}>
                <div style={divStyle}>
                    <h1>Form</h1>
                    <input type="text" placeholder="First Name" name="firstName" onChange={handleInputChange}></input>
                </div>
                <div style={divStyle}>
                    <input type="text" placeholder="Last Name" name="lastName" onChange={handleInputChange}></input>
                </div>
                <div style={divStyle}>
                    <button onClick={sendDatos} value="send">Send</button>
                </div>
            </div>
            <MaterialTable
                icons={tableIcons}
                columns={columns}
                data={people}
                title="People"
                options={{exportButton: true}}
                editable={{
                    onRowAdd: newData =>
                        new Promise((resolve, reject) => {
                            setTimeout(() => {
                            //setData([...data, newData]);
                            
                            resolve();
                            }, 1000)
                        }),
                        onRowUpdate: (newData, oldData) =>
                        new Promise((resolve, reject) => {
                            setTimeout(() => {
                            //const dataUpdate = [...data];
                            const index = oldData.tableData.id;
                            //dataUpdate[index] = newData;
                            //setData([...dataUpdate]);
                
                            resolve();
                            }, 1000)
                        }),
                        onRowDelete: oldData =>
                        new Promise((resolve, reject) => {
                            setTimeout(() => {
                            //const dataDelete = [...data];
                            const index = oldData.tableData.id;
                            //dataDelete.splice(index, 1);
                            //setData([...dataDelete]);
                            
                            resolve()
                            }, 1000)
                        }),
                    }}
            />
        </Fragment>
    );
};

export default FormComponent;
