import React, { useState, useEffect }  from 'react';
import { Row, Col } from 'react-bootstrap'
import toast, { Toaster } from 'react-hot-toast';

import { 
    ToggleButton, 
    ToggleButtonGroup, 
    Box,
    Paper,
    Pagination,
} from '@mui/material';

import { ViewList as ViewListIcon, ViewModule as ViewModuleIcon, } from '@mui/icons-material';

import { default as useAuth } from '../Auth/useAuth';
import { Service } from '../Utils/HTTP';

import Express from '../Components/Modal/AgregarExpress';
import Manual from '../Components/Modal/AgregarManual';

import Editar from '../Components/Modal/EditPlaza';
import Eliminar from '../Components/Modal/EliminarPlaza';
import Mostrar from '../Components/Modal/MostrarPlaza';

import { ListMode } from '../Components/Puestos/ListMode'
import { GridMode } from '../Components/Puestos/GridMode'
import { Add as AddIcon, } from '@mui/icons-material/'

function Divide(arregloOriginal){
    const LONGITUD_PEDAZOS = 7;
    let arregloDeArreglos = [];
    for (let i = 0; i < arregloOriginal.length; i += LONGITUD_PEDAZOS) {
        let pedazo = arregloOriginal.slice(i, i + LONGITUD_PEDAZOS);
        arregloDeArreglos.push(pedazo);
    }
    return arregloDeArreglos
}

export function Puestos() {

    const Complete =  (status) => {

        if(!status){
            toast.error('Ups creo que ocurrio un error, intentalo nuevamente')
        }

        let rest = new Service("/plaza/getall")
        rest
            .get(token)
            .then(({data}) => {
                let entries = data.map( e => {
                    return {
                        nombre : e.nombrepuesto,
                        description : e.notas,
                        id : e.id,
                        created: e.create_day,
                        data: e
                    };
                })
                setData(Divide(entries))
            })
            .catch((error) => {
                console.log('error fetching data  ', error );
            })

        toast.success('Puesto agregado exitosamente')
    } 

    const auth = useAuth();
    const [data, setData] = useState([]);
    const [page, setPage] = useState(1);
    const token = auth.getToken();

    const changePage = ( _ , value) => setPage(value);

    useEffect(() => {

        let rest = new Service("/plaza/getall")
        rest
            .get(token)
            .then(({data}) => {
                let entries = data.map( e => {
                    return {
                        nombre : e.nombrepuesto,
                        description : e.notas,
                        id : e.id,
                        created: e.create_day,
                        data: e
                    };
                })
                setData(Divide(entries))
            })
            .catch((error) => {
                console.log('error fetching data  ', error );
            })


    },[token])

    // const [alignment, setAlignment] = React.useState('list');
    const [alignment, setAlignment] = React.useState('grid');

    const handleChange = (_event, newAlignment) => setAlignment(newAlignment)

    const children = [
        <ToggleButton value="list" key="list">
            <ViewListIcon />
        </ToggleButton>,
        <ToggleButton value="grid" key="grid">
            <ViewModuleIcon/>
        </ToggleButton>,
    ];

    const control = {
        value: alignment,
        onChange: handleChange,
        exclusive: true,
    };

    let [puesto, setPuesto] = React.useState(false);

    let [manual, setManual] = React.useState(false);
    let [expres, setExpress] = React.useState(false);

    let [edit, setEdit] = React.useState(false);
    let [del, setDelete] = React.useState(false);
    let [show, setShow] = React.useState(false);

    return (
        <div className="content-section">
            <div className="main">
                <Box sx={{ width: '100%' }}>
                    <Paper sx={{ width: '100%', mb: 2, padding : 2, height: '100%', minHeight:'95vh' }}>

                        <Row style={{paddingBottom : 15}}>
                            <Col md="2" sm="2" xs="2">
                                <div className="breadcrumb-header">
                                    <Box sx={{ float : 'left',display: 'flex', flexDirection: 'column', alignItems: 'center', '& > :not(style) + :not(style)': { mt: 2 }, }} >
                                        <ToggleButtonGroup size="small" {...control}>
                                            {children}
                                        </ToggleButtonGroup>
                                    </Box>
                                </div>
                            </Col>
                            <Col md="10" sm='10' xs="10">
                                <div className="add_producto">
                                    <div onClick={() => setManual(true) } className="btn_add_producto"> 
                                        <span className="btn_plaza_common" >Agregar manual <AddIcon fontSize="small"/></span> 
                                    </div>
                                </div>
                                <div onClick={() => setExpress(true) } className="add_producto">
                                    <div className="btn_add_producto"> 
                                        <span className="btn_plaza_common">Agregar express <AddIcon fontSize="small"/></span> 
                                    </div>
                                </div>
                            </Col>
                        </Row>
                        <div className={`main_productos ${ alignment === 'grid' ? 'activar_vista' : 'desactivar_vista'  }`} id="grid_view">
                            <Row>
                                <GridMode
                                    showing={alignment}
                                    data={data}
                                    index={page - 1}
                                    setPuesto={setPuesto}
                                    setEdit={setEdit}
                                    setDelete={setDelete}
                                    setShow={setShow}
                                    />
                            </Row>
                        </div>
                        <div className={`main_list_products ${alignment === 'list' ?  'activar_vista' : 'desactivar_vista'}`} id="list_view_products">
                            <Row>
                                <ListMode 
                                    showing={alignment}
                                    data={data}
                                    index={page - 1}
                                    setPuesto={setPuesto}
                                    setEdit={setEdit}
                                    setDelete={setDelete}
                                    setShow={setShow}
                                    />
                            </Row>
                        </div>

                        <Pagination 
                            sx={{
                                "& ul" :{
                                    paddingTop: "20px",
                                    justifyContent: "center"
                                }
                            }}
                            siblingCount={2} 
                            boundaryCount={2}
                            shape='rounded' 
                            count={data.length} 
                            page={page} 
                            onChange={changePage} 
                            />

                    </Paper>
                </Box>

            </div>

            <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false) } />

            <Manual Complete={Complete} visible={manual} onClose={() => setManual(false)}/>

            <Editar   puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
            <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
            <Mostrar  puesto={puesto} visible={show} onClose={() => setShow(false)} />

            <Toaster  position="bottom-right" reverseOrder={false} />

        </div>
    )
}
