import React, { Fragment, useEffect, useState, useCallback } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
import { makeStyles, withStyles, createStyles } from '@material-ui/styles';
import { Grid, Container, Box, Button, TextField, Typography, InputLabel, Select, MenuItem, FormControl, TableContainer, Table, TableHead, TableRow, TableBody, TableCell } from '@material-ui/core';

const MySwal = withReactContent(Swal);

const RegistroAutosComponent = () => {
    const apiUrl = "http://localhost:5000/api";
    const apiUrlAutos = "/auto";
    const apiUrlMarcas = "/marca";

    const[autos, setAutos] = useState([]);
    const[marcas, setMarcas] = useState([]);

    const[patente, setPatente] = useState("");
    const[anio, setAnio] = useState("");
    const[marca, setMarca] = useState("");

    const [guardarBtnDisabled, setGuardarBtnDisabled] = useState(true);

    const changeButtonState = useCallback(() => { 
        setGuardarBtnDisabled(patente === "" || anio === "" || marca === "");
    }, [patente, anio, marca]);

    const handleInputChangePatente = (event) => {
        setPatente(event.target.value);
    }

    const handleInputChangeAnio = (event) => {
        setAnio(event.target.value);
    }

    const handleInputChangeMarca = (event) => {
        setMarca(event.target.value);
    }

    useEffect(() => {
        changeButtonState();
    }, [changeButtonState, patente]);

    useEffect(() => {
        changeButtonState();
    }, [changeButtonState, anio]);

    useEffect(() => {
        changeButtonState();
    }, [changeButtonState, marca]);

    async function getAutos() {
        try {
            const response = await axios.get(apiUrl + apiUrlAutos);
            if (response.status === 200) {
                setAutos(response.data.auto);
            }
        }
        catch (error) {
            console.error(error);
        }
    }

    async function getMarcas() {
        try {
            const response = await axios.get(apiUrl + apiUrlMarcas);
            if (response.status === 200) {
                setMarcas(response.data.marca);
            }
        }
        catch (error) {
            console.error(error);
        }
    }

    function guardar() {
        axios.post(apiUrl + apiUrlAutos, {
            patente: patente,
            anio: anio,
            marca: marca
        })
        .then(function (response) {
            if (response.status === 200) {
                MySwal.fire({
                    title: <p>Guardada!</p>,
                    text: 'El auto fue guardada!',
                    icon: 'success'
                });
                setPatente("");
                setAnio("");
                setMarca("");
                getAutos();
                getMarcas();
            }
            else {
                MySwal.fire({
                    title: <p>Error!</p>,
                    text: response.data.mensaje,
                    icon: 'error'
                });
            }
        })
        .catch(function (error) {
            MySwal.fire({
                title: <p>Error!</p>,
                text: error.response.data.mensaje,
                icon: 'error'
            });
        });
    }

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

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

    const useStyles = makeStyles(theme => ({
        root: {},
        tableHeader: {
            backgroundColor: '#0468aa',
            color: '#FFFFFF',
            fontWeight: 'bold'
        },
        tableBorder: {
            borderWidth: 1,
            borderColor: 'DarkGray',
            borderStyle: 'solid',
        },
        tableRow1: {
            backgroundColor: '#FFFFFF'
        },
        tableRow2: {
            backgroundColor: '#e6e6e6'
        }
    }));

    const StyledTableRow = withStyles(theme =>
        createStyles({
            root: {
                '&:nth-of-type(odd)': {
                    backgroundColor: "white",
                },
                '&:nth-of-type(even)': {
                    backgroundColor: "LightGrey",
                },
            },
        }),
    )(TableRow);

    const classes = useStyles();

    return (
        
        <Fragment>
            <Container maxWidth="md">
                <Grid container spacing={2}>
                    <Grid item xs={12} md={12}>
                        <Box mt={2}>
                            <Typography variant="h6">
                                Registro de Autos
                            </Typography>
                        </Box>
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            id="patente"
                            label="Patente"
                            value={patente}
                            onChange={handleInputChangePatente}
                            variant="outlined"
                            fullWidth
                        />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            id="anio"
                            label="Año"
                            value={anio}
                            onChange={handleInputChangeAnio}
                            variant="outlined"
                            fullWidth
                        />
                    </Grid>
                    <Grid item xs={12}>
                        <FormControl fullWidth variant="outlined">
                            <InputLabel>Marca</InputLabel>
                            <Select
                                id="marca"
                                value={marca}
                                label="Marca"
                                onChange={handleInputChangeMarca}
                            >
                                <MenuItem value=""></MenuItem>
                                {marcas.map((marca) => (
                                    <MenuItem value={marca._id}>{marca.descripcion}</MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                    </Grid>
                    <Grid item xs={12} sm={2}>
                        <Button disabled={guardarBtnDisabled} variant="contained" color="primary" fullWidth onClick={guardar}>
                            Guardar
                        </Button>
                    </Grid>
                </Grid>

                <Grid item xs={12} md={12} className="material-table">
                    <Box mt={3}>
                        <TableContainer>
                            <Table aria-label="tabla de autos">
                                <TableHead>
                                <TableRow>
                                    <TableCell className={`${classes.tableBorder} ${classes.tableHeader}`} align="center">Marca</TableCell>
                                    <TableCell className={`${classes.tableBorder} ${classes.tableHeader}`} align="center">Patente</TableCell>
                                    <TableCell className={`${classes.tableBorder} ${classes.tableHeader}`} align="center">Año</TableCell>
                                </TableRow>
                                </TableHead>
                                <TableBody>
                                {autos.map((auto, index) => (
                                    <StyledTableRow key={auto._id}>
                                        <TableCell className={classes.tableBorder} component="th" scope="row">
                                            {auto.marca.descripcion}
                                        </TableCell>
                                        <TableCell className={classes.tableBorder} align="left">{auto.patente}</TableCell>
                                        <TableCell className={classes.tableBorder} align="left">{auto.anio}</TableCell>
                                    </StyledTableRow>
                                ))}
                                </TableBody>
                            </Table>
                            </TableContainer>
                    </Box>
                </Grid>
            </Container>
        </Fragment>
    );
};

export default RegistroAutosComponent;
