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 ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import { Button } from '@mui/material';
import { useDispatch, useSelector } from 'react-redux';
import { authSlice, cartSlice } from '../api/api';
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);
  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 aria-label="cart">
                <StyledBadge badgeContent={goodsInCart} color="primary">
                  <ShoppingCartIcon sx={{ color: 'white', fontSize: '30px' }} />
                </StyledBadge>
              </IconButton>
            </Link>
          </Box>
          {token ?
            <LinkButton to="/" text="Logout" click={onLogout}/> : <>
              <LinkButton to="login" text="Login" />
              <LinkButton to="register" text="Registration" />
            </>
          }

          {/* <button id="logout" className="button">Logout</button> */}
        </Box>
      </Toolbar>
    </AppBar>

  )
}
