import React from 'react';
import { Link } from 'react-router-dom';
import Badge from '@mui/material/Badge';
import { styled } from '@mui/material/styles';
import IconButton from '@mui/material/IconButton';
import { ShoppingCart, AccountCircle } from '@mui/icons-material/';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import { useDispatch, useSelector } from 'react-redux';
import { authSlice } from '../store/authSlice';
import { cartSlice } from '../store/cartSlice';
import DrawUserName from './DrawUserName';
import LinkButton from './LinkButton';

const StyledBadge = styled(Badge)(({ theme }) => ({
  '& .MuiBadge-badge': {

    top: 24,
    border: `2px solid ${theme.palette.background.paper}`,
    padding: '0 4px',
  },
}));
export default function Header() {
  const dispatch = useDispatch();
  const goodsInCart = useSelector(state => state.cart.goodsCount);
  const onLogout = () => {
    dispatch(authSlice.actions.logout());
    dispatch(cartSlice.actions.clearCart());
  }
  const token = useSelector(state => state.auth.token);
  const userId = useSelector(state => state.auth?.payload?.sub?.id);
  const admin = useSelector(state => state.auth?.payload?.sub?.acl.includes('admin'));
  return (
    <AppBar position="static">
      <Toolbar>
        <Box sx={{ flexGrow: 1 }}>
          <Link to="/"><img src="/images/logo.jpg" /></Link>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <DrawUserName />
          <Box sx={{ mx: 1, my: 2 }}>
            <Link to="cart">
              <IconButton>
                <StyledBadge badgeContent={goodsInCart} color="primary">
                  <ShoppingCart sx={{ color: 'white', fontSize: '30px' }} />
                </StyledBadge>
              </IconButton>
            </Link>
          </Box>
          {token ?
            <>
              {!admin && <Link to={`/user/${userId}`}>
                <IconButton><AccountCircle sx={{ color: 'white', fontSize: '30px' }} /></IconButton>
              </Link>}
              <LinkButton to="/" click={onLogout}>Logout</LinkButton>
            </>
            :
            <>
              <LinkButton to="login">Login</LinkButton>
              <LinkButton to="register">Registration</LinkButton>
            </>
          }
        </Box>
      </Toolbar>
    </AppBar>

  )
}
