import * as React from 'react';
import { styled, useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import MuiAppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import CssBaseline from '@mui/material/CssBaseline';
import List from '@mui/material/List';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import InboxIcon from '@mui/icons-material/MoveToInbox';
import MailIcon from '@mui/icons-material/Mail';
import Logo from '../../../public/Img/Logo/Logo.jpg';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import CircleIcon from '@mui/icons-material/Circle';
const drawerWidth = 240;
import Badge from '@mui/material/Badge';
import CarrinhoController from '@/Tools/Carrinho';
import '../../css/app.css';
import Video from '../../../public/Img/Video/videoPc.mp4'
import { router } from '@inertiajs/react';
import LoginIcon from '@mui/icons-material/Login';
import PersonAddAlt1Icon from '@mui/icons-material/PersonAddAlt1';
import LogoutIcon from '@mui/icons-material/Logout';
import Button from '@mui/material/Button';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import AlertasGenericos from '../Components/Alertas';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import CallIcon from '@mui/icons-material/Call';
import Modal from '@mui/material/Modal';
import Grid from '@mui/material/Grid';
import PlaceIcon from '@mui/icons-material/Place';


const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })(
    ({ theme, open }) => ({
        flexGrow: 1,
        padding: theme.spacing(3),
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen,
        }),
        marginRight: -drawerWidth,
        ...(open && {
            transition: theme.transitions.create('margin', {
                easing: theme.transitions.easing.easeOut,
                duration: theme.transitions.duration.enteringScreen,
            }),
            marginRight: 0,
        }),
        /**
         * This is necessary to enable the selection of content. In the DOM, the stacking order is determined
         * by the order of appearance. Following this rule, elements appearing later in the markup will overlay
         * those that appear earlier. Since the Drawer comes after the Main content, this adjustment ensures
         * proper interaction with the underlying content.
         */
        position: 'relative',
    }),
);

const AppBar = styled(MuiAppBar, {
    shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
    transition: theme.transitions.create(['margin', 'width'], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),
    ...(open && {
        width: `calc(100% - ${drawerWidth}px)`,
        transition: theme.transitions.create(['margin', 'width'], {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
        marginRight: drawerWidth,
    }),
}));

const DrawerHeader = styled('div')(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-start',
}));

const style = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: 400,
    bgcolor: 'background.paper',
    border: '2px solid #000',
    boxShadow: 24,
    p: 4,
};

export default function PersistentDrawerRight({ horario_abertura, mostrar_video = true, logado = false, pedido_em_andamento = false, parametros_da_empresa }) {
    const theme = useTheme();
    const [open, setOpen] = React.useState(false);

    // MODAL
    const [alertaAberto, setAlertaAberto] = React.useState(false);
    const [alertaTexto, setAlertaTexto] = React.useState('');
    const [quantidadeDeItensNoCarrinho, setQuantidadeDeItensNoCarrinho] = React.useState(0)

    // MODAL DE DADOS DO ENDEREÇO
    const [openModalEndereco, setopenModalEndereco] = React.useState(false);
    const handleOpenModalEndereco = () => setopenModalEndereco(true);
    const handleCloseModalEndereco = () => setopenModalEndereco(false);

    const handleDrawerOpen = () => {
        setOpen(true);
    };

    const handleDrawerClose = () => {
        setOpen(false);
    };

    //ALERTAS;
    const mostrarAlerta = (texto) => {
        setAlertaTexto(texto);
        setAlertaAberto(true);
    };

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAlertaAberto(false);
    };

    React.useEffect(() => {
        // busca os daods do carrinho.
        async function carregaDados() {

            let resposta = await CarrinhoController.VerProdutos();

            if (resposta == 'erro') {
                mostrarAlerta("Ocorreu um erro ao buscar os dados do seu carrinho.")
                return
            }

            if (resposta == 'sem_itens') {
                return
            }
            setQuantidadeDeItensNoCarrinho(resposta.length)
        }
        carregaDados()
    }, [])

    function NavegarParaCarrinho() {
        let dados_do_carrinho = CarrinhoController.VerProdutos();

        if (dados_do_carrinho == 'sem_itens') {
            mostrarAlerta("Você não possui itens no carrinho.")
            return
        }
        if (dados_do_carrinho == 'erro') {
            mostrarAlerta("Você não possui itens no carrinho.")
            return
        }
        router.get(route('ver.carrinho'), { dados: dados_do_carrinho });

    }

    // Volta para home 
    function VoltarParaHome() {
        router.get(route('Pagina.de.inicio'));
    }

    function FazerLogin() {
        router.get(route('login'));
    }

    function FazerCadastro() {

        router.get(route('register'));
    }

    function FazerLogOff() {

        router.get(route('fazer.logOff'));
    }

    function AbrirModalContatos() {
        handleOpenModalEndereco();
    }

    return (
        <>
            {/* MODAL DE DADOS DE CONTATOS  */}
            <div>
                <Modal
                    keepMounted
                    open={openModalEndereco}
                    onClose={handleCloseModalEndereco}
                    aria-labelledby="keep-mounted-modal-title"
                    aria-describedby="keep-mounted-modal-description"
                >
                    {/* {console.log("teste de dadis", parametros_da_empresa)} */}
                    <Box sx={style}>
                        <Box>
                            <Grid
                                container
                                owSpacing={1}
                            >
                                <Grid item xs={12}>
                                    <Button
                                        variant='text'
                                        sx={{ color: 'black' }}
                                        startIcon={<PlaceIcon sx={{ color: 'red' }} />}
                                    >
                                        {parametros_da_empresa.emp_logradouro != undefined ?
                                            `${parametros_da_empresa.emp_logradouro}, N° ${parametros_da_empresa.emp_numero} - ${parametros_da_empresa.emp_bairro != undefined ? parametros_da_empresa.emp_bairro : parametros_da_empresa.bairro}  `
                                            :
                                            parametros_da_empresa.endereco
                                        }

                                    </Button>
                                </Grid>
                                <Grid item xs={12}>
                                    <Button
                                        variant='text'
                                        sx={{ color: 'black' }}
                                        startIcon={<CallIcon sx={{ color: 'red' }} />}
                                    >
                                        {parametros_da_empresa.emp_telefone1 != undefined ?
                                            parametros_da_empresa.emp_telefone1
                                            :
                                            parametros_da_empresa.telefone
                                        }

                                    </Button>
                                </Grid>
                                <Grid sx={{ background: 'blue' }} item xs={12}>
                                    <Button
                                        onClick={() => { handleCloseModalEndereco() }}
                                        variant='contained'
                                        sx={{ width: '100%' }}
                                    >
                                        OK
                                    </Button>

                                </Grid>
                            </Grid>
                        </Box>
                    </Box>
                </Modal>
            </div>

            {/* ALERTAS*/}
            <AlertasGenericos
                aberto={alertaAberto}
                texto={alertaTexto}
                handleClose={handleClose}
            />

            <Box sx={{ display: 'flex' }}>
                <CssBaseline />
                <AppBar position="fixed" open={open} style={{ backgroundColor: 'white', color: 'black' }}>
                    <Toolbar>

                        <Typography variant="h6" noWrap sx={{ flexGrow: 1 }} component="div">
                            <img onClick={VoltarParaHome} style={{ width: 185, cursor: 'pointer' }} src={Logo}></img>
                        </Typography>

                        <>
                            <Button style={{ width: 170, color: 'red', display: 'flex', justifyContent: 'space-around' }} onClick={NavegarParaCarrinho}  >
                                Meu carrinho
                                <Badge
                                    className={quantidadeDeItensNoCarrinho > 0 ? 'bounce' : "Carrinho"}
                                    badgeContent={quantidadeDeItensNoCarrinho > 0 ? quantidadeDeItensNoCarrinho : 0}
                                    color="primary" sx={{ marginRight: '1%', color: 'red' }}>
                                    <ShoppingCartIcon color="red" />
                                </Badge>
                            </Button>

                            {pedido_em_andamento ?
                                <Button onClick={() => { router.get(route('ver.pedido')) }} style={{ width: 170, color: 'red', display: 'flex', justifyContent: 'space-around' }}>
                                    Meu pedidos
                                    <NotificationsActiveIcon className='bell' color="red" />
                                </Button>
                                :
                                null
                            }
                        </>


                        {/* SE O USUÁRIO ESTIVER LOGADO VAI MOSTRAR O BTN DE FAZER LOGOFF */}
                        {logado ?

                            <>
                                <Box sx={{ width: '30%', display: 'flex', justifyContent: 'space-around' }}>
                                    <section onClick={() => { router.get(route('ver.meu.perfil')) }}>
                                        <Button endIcon={<AccountCircleIcon sx={{ color: 'red' }} />} color='error' variant="outlined">Meu perfil</Button>
                                    </section>
                                    <section onClick={AbrirModalContatos}>
                                        <Button endIcon={<CallIcon sx={{ color: 'red' }} />} color='error' variant="outlined">Contatos</Button>
                                    </section>
                                    <section onClick={FazerLogOff}>
                                        <Button endIcon={<LogoutIcon sx={{ color: 'red' }} />} color='error' variant="outlined">Sair</Button>
                                    </section>
                                </Box>
                            </>
                            :
                            <>
                                <section onClick={FazerLogin}>
                                    <Button endIcon={<LoginIcon sx={{ color: 'red' }} />} color='error' variant="outlined">Login</Button>
                                </section>
                                <section style={{ marginRight: 17, marginLeft: 17 }} onClick={FazerCadastro}>
                                    <Button endIcon={<PersonAddAlt1Icon sx={{ color: 'red' }} />} color='error' variant="outlined">Cadastro</Button>
                                </section>
                                <section onClick={AbrirModalContatos}>
                                    <Button endIcon={<CallIcon sx={{ color: 'red' }} />} color='error' variant="outlined">Contatos</Button>
                                </section>
                            </>
                        }
                    </Toolbar>
                </AppBar>
                <Drawer
                    sx={{
                        width: drawerWidth,
                        flexShrink: 0,
                        '& .MuiDrawer-paper': {
                            width: drawerWidth,
                        },
                    }}
                    variant="persistent"
                    anchor="right"
                    open={open}
                >
                    <DrawerHeader>
                        <IconButton onClick={handleDrawerClose}>
                            {theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
                        </IconButton>
                    </DrawerHeader>
                    <Divider />
                    <List>
                        {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
                            <ListItem key={text} disablePadding>
                                <ListItemButton>
                                    <ListItemIcon>
                                        {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                                    </ListItemIcon>
                                    <ListItemText primary={text} />
                                </ListItemButton>
                            </ListItem>
                        ))}
                    </List>
                    <Divider />
                    <List>
                        {['All mail', 'Trash', 'Spam'].map((text, index) => (
                            <ListItem key={text} disablePadding>
                                <ListItemButton>
                                    <ListItemIcon>
                                        {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                                    </ListItemIcon>
                                    <ListItemText primary={text} />
                                </ListItemButton>
                            </ListItem>
                        ))}
                    </List>
                </Drawer>
            </Box>

            {/* SE DEVE OU NÃO MOSTRAR O VÍDEO  */}
            {mostrar_video ?
                <video
                    loop
                    autoPlay
                    muted
                    playsInline
                    style={{
                        margin: 'auto',
                        width: '100%',
                        height: '350px',  // ou a altura desejada
                        objectFit: 'cover'  // Ajusta o vídeo para cobrir o container de forma proporcional
                    }}
                >
                    <source src={Video} type="video/mp4" />
                    Seu navegador não suporta o elemento de vídeo.
                </video>
                :
                null
            }

            {horario_abertura != undefined ?
                <section style={{ textAlign: 'center', margin: 'auto', width: '90%', marginBottom: -78 }}>

                    {open ? null :
                        <Typography>
                            {
                                horario_abertura.aberto === undefined ? null : (
                                    <>
                                        {horario_abertura.aberto ? (
                                            <CircleIcon sx={{ width: 15, marginRight: 1, color: 'green', marginTop: -0.5 }} />
                                        ) : (
                                            <CircleIcon sx={{ width: 15, marginRight: 1, color: 'red', marginTop: -0.5 }} />
                                        )}
                                        {horario_abertura.texto}
                                    </>
                                )
                            }
                        </Typography>
                    }

                </section>
                :
                null
            }
        </>
    );
}



// {open ? null :
//     <Typography >
//         {
//             horario_abertura.aberto === undefined ? null : (
//                 <>
//                     {horario_abertura.aberto ? (
//                         <CircleIcon sx={{ width: 15, marginRight: 1, color: 'green', marginTop: -0.5 }} />
//                     ) : (
//                         <CircleIcon sx={{ width: 15, marginRight: 1, color: 'red', marginTop: -0.5 }} />
//                     )}
//                     {horario_abertura.texto}
//                 </>
//             )
//         }
//     </Typography>
// }