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

import {
    ToggleButton, ToggleButtonGroup, Box,
    Paper, Pagination,Chip
} 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 { Divide } from '../Utils/Paginate';

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/'

import { Loading } from '../Components/Generics/loading'
import { ErrorMessage } from '../Components/Generics/Error'

import { useQuery } from 'react-query';

export function Puestos() {

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

    const getAll = async () => {
        let rest = new Service("/plaza/getall")
        let response =  await rest.getQuery(token.current); 
        return response;
    }

    const { isLoading, error, data : result } = useQuery('puestos', getAll);
    const changePage = useCallback((_, value) => setPage(value),[]);
    const [alignment, setAlignment] = React.useState('grid');
    const handleChange = useCallback((_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 [manual, setManual] = React.useState(false);
    let [expres, setExpress] = React.useState(false);

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

    const toggle = useCallback((type,puesto) => {
        setPuesto(puesto)
        switch(type){
            case "VER": {
                setShow(!show);
                break;
            }
            case "EDIT": {
                setEdit(!edit)
                break;
            }
            case "DEL": {
                setDelete(!del)
                break;
            }
            default: break;
        }
    },[edit,del,show])

    if (isLoading){
        return(
            <Paper sx={{ mb: 2, padding: 2, height: '100%', minHeight: '95vh' }}>
                <main id="loading_or_content">
                    <Loading />
                </main>
            </Paper>
        )
    } 

    if (error) {
        return (
            <Paper sx={{ mb: 2, padding: 2, height: '100%', minHeight: '95vh' }}>
                <main id="loading_or_content">
                    <ErrorMessage/>
                </main>
            </Paper>
        )
    }

    const total_items = Divide(result.data).length

    return (
        <div className="content-section">
            <div className="main">
                <Box>
                    <Paper sx={{ mb: 2, padding: 2, }}>

                        <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>
                            <div className={`main_productos ${alignment === 'grid' ? 'activar_vista' : 'desactivar_vista'}`} id="grid_view">
                                <Row>
                                    <GridMode
                                        toggle={toggle}
                                        showing={alignment}
                                        data={Divide( result.data )}
                                        index={page - 1}
                                    />
                                </Row>
                            </div>
                            <div className={`main_list_products ${alignment === 'list' ? 'activar_vista' : 'desactivar_vista'}`} id="list_view_products">
                                <Row>
                                    <ListMode
                                        toggle={toggle}
                                        showing={alignment}
                                        data={Divide( result.data )}
                                        index={page - 1}
                                    />
                                </Row>
                            </div>

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

                                <Chip label={"Total: "+ ( result? result.data.length : 0 ) } />
                            </div>

                        </div>
                    </Paper>
                </Box>
            </div>

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

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

            <Toaster position="bottom-right" />

        </div>
    )
}
