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 MenuIcon from '@mui/icons-material/Menu';
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 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 AlertasGenericos from '../Components/Alertas'
import '../../css/app.css';
import { router } from '@inertiajs/react';
import PersonIcon from '@mui/icons-material/Person';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import LoginIcon from '@mui/icons-material/Login';
import LogoutIcon from '@mui/icons-material/Logout';
import CleaningServicesIcon from '@mui/icons-material/CleaningServices';
import CallIcon from '@mui/icons-material/Call';
import PlaceIcon from '@mui/icons-material/Place';
import Modal from '@mui/material/Modal';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import { Height } from '@mui/icons-material';

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%',
  height:170,
  transform: 'translate(-50%, -50%)',
  width: '97%',
  bgcolor: 'white',
  boxShadow: 24,
  p: 2,
};


export default function PersistentDrawerRight({ horario_abertura = undefined, 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 [quantidadeDeItensNoCarrinho, setQuantidadeDeItensNoCarrinho] = React.useState(0)
  const [alertaTexto, setAlertaTexto] = React.useState('');
  const [tipoAlerta, setTipoAlerta] = React.useState('');

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  // MODAL DE DADOS DO ENDEREÇO
  const [openModalEndereco, setopenModalEndereco] = React.useState(false);
  const handleOpenModalEndereco = () => setopenModalEndereco(true);
  const handleCloseModalEndereco = () => setopenModalEndereco(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') {
        setTipoAlerta('warning');
        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') {
      setTipoAlerta('warning');
      mostrarAlerta("Você não possui itens no carrinho.")
      return
    }
    if (dados_do_carrinho == 'erro') {
      setTipoAlerta('warning');
      mostrarAlerta("Você não possui itens no carrinho.")
      return
    }
    router.get(route('ver.carrinho'), { dados: dados_do_carrinho });

  }
  // CONTINUAR A FAZER BOTÕES DA LATERAL

  // Volta para home 
  function VoltarParaHome() {
    router.get(route('Pagina.de.inicio'));
  }

  async function AcoesDoMenuLateral(acao) {

    switch (acao) {
      case 'Sair':
        router.get(route('fazer.logOff'));
        return
      case 'Login':
        router.get(route('login'));
        return
      case 'Cadastro':
        router.get(route('register'));
        return
      case 'Meus pedidos':
        router.get(route('ver.pedido'));
        return
      case 'Meu perfil':
        router.get(route('ver.meu.perfil'));
        return
      case 'Contatos':
        handleOpenModalEndereco();
        return
      case 'Limpar dados':
        await localStorage.removeItem("user_pt")
        await localStorage.removeItem("default_pt")
        await localStorage.removeItem("carrinho_")
        await localStorage.removeItem("steps")
        await localStorage.removeItem("tamanho")
        await localStorage.removeItem("meia_pizza")
        setTipoAlerta('success');
        mostrarAlerta("Dados limpos !")
        window.location.reload();
        return
      default:
        break;
    }

  }

  function AbrirModalContatos() {
    handleOpenModalEndereco();
  }


  return (
    <>
      {/* ALERTAS*/}
      <AlertasGenericos
        aberto={alertaAberto}
        texto={alertaTexto}
        handleClose={handleClose}
        tipo={tipoAlerta}

      />

      {/* MODAL DE DADOS DE CONTATOS  */}
      <div>
        <Modal
          keepMounted
          open={openModalEndereco}
          onClose={handleCloseModalEndereco}
          aria-labelledby="keep-mounted-modal-title"
          aria-describedby="keep-mounted-modal-description"
        >
          <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},${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 item xs={12}>
                  <Button
                    onClick={() => { handleCloseModalEndereco() }}
                    variant='contained'
                    sx={{ width: '100%', marginTop:'7%' }}
                  >
                    OK
                  </Button>

                </Grid>
              </Grid>
            </Box>
          </Box>
        </Modal>
      </div>


      <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: 150 }} src={Logo}></img>
            </Typography>

            {pedido_em_andamento ?
              <NotificationsActiveIcon onClick={() => { router.get(route('ver.pedido')) }}
                sx={{ marginRight: 3 }} className='bell' color="red" />
              :
              null
            }

            {open ? null :

              <>

                {/* <Button endIcon={<CallIcon sx={{ color:'red', fontWeight: 700  }}></CallIcon>}>

                </Button> */}
                <CallIcon onClick={AbrirModalContatos} sx={{ marginRight: '7%', color: 'red' }}></CallIcon>

                <Badge
                  onClick={NavegarParaCarrinho}
                  className={quantidadeDeItensNoCarrinho > 0 ? 'bounce' : "Carrinho"}
                  badgeContent={quantidadeDeItensNoCarrinho > 0 ? quantidadeDeItensNoCarrinho : 0}
                  color="primary" sx={{ marginRight: '5%', color: 'red' }}
                >
                  <ShoppingCartIcon color="red" />
                </Badge>


              </>


            }

            <IconButton
              color="inherit"
              aria-label="open drawer"
              edge="end"
              onClick={handleDrawerOpen}
              sx={{ ...(open && { display: 'none' }) }}
            >
              <MenuIcon sx={{ color: 'red' }} />
            </IconButton>



          </Toolbar>


          {open ? null :
            <Typography sx={{ textAlign: 'center' }}>
              {
                horario_abertura === 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>
          }
        </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 />
          {
            logado ?
              <List>
                {['Meu perfil', 'Meus pedidos', 'Limpar dados', 'Sair', 'Contatos'].map((text, index) => (
                  <ListItem key={text} disablePadding>
                    <ListItemButton onClick={() => { AcoesDoMenuLateral(text) }}>
                      <ListItemIcon>
                        {text == 'Meu perfil' ? <PersonIcon></PersonIcon> : null}
                        {text == 'Meus pedidos' ? <NotificationsActiveIcon></NotificationsActiveIcon> : null}
                        {text == 'Limpar dados' ? <CleaningServicesIcon></CleaningServicesIcon> : null}
                        {text == 'Sair' ? <LogoutIcon></LogoutIcon> : null}
                        {text == 'Contatos' ? <CallIcon></CallIcon> : null}

                        {/* {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} */}
                      </ListItemIcon>
                      <ListItemText primary={text} />
                    </ListItemButton>
                  </ListItem>
                ))}
              </List>
              :
              <List>
                {['Meu perfil', 'Cadastro', 'Login', 'Limpar dados', 'Contatos'].map((text, index) => (
                  <ListItem key={text} disablePadding>
                    <ListItemButton onClick={() => { AcoesDoMenuLateral(text) }}>
                      <ListItemIcon>
                        {text == 'Meu perfil' ? <PersonIcon></PersonIcon> : null}
                        {text == 'Cadastro' ? <PersonAddIcon></PersonAddIcon> : null}
                        {text == 'Login' ? <LoginIcon></LoginIcon> : null}
                        {text == 'Limpar dados' ? <CleaningServicesIcon></CleaningServicesIcon> : null}
                        {text == 'Contatos' ? <CallIcon></CallIcon> : null}

                        {/* {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} */}
                      </ListItemIcon>
                      <ListItemText primary={text} />
                    </ListItemButton>
                  </ListItem>
                ))}
              </List>
          }
          <Divider />
        </Drawer>
      </Box>
    </>
  );
}
