import { AccountCircle, Translate } from '@mui/icons-material';
import {
  AppBar,
  Avatar,
  Box,
  CircularProgress,
  IconButton,
  Link as MUILink,
  Toolbar,
  useScrollTrigger,
} from '@mui/material';
import { Link, useRouterState } from '@tanstack/react-router';
import { cloneElement, FC, ReactElement, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Api from '../../api/Api';
import LanguageMenu from '../Menus/Language/LanguageMenu';
import UserMenu from '../Menus/User/UserMenu';

const ElevationScroll = ({ children }: { children: ReactElement }) => {
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 0,
  });

  return cloneElement(children, {
    elevation: trigger ? 4 : 0,
  });
};

const Header: FC = () => {
  const [anchorUserMenu, setAnchorUserMenu] = useState<null | HTMLElement>(null);
  const [anchorLanguageMenu, setAnchorLanguageMenu] = useState<null | HTMLElement>(null);

  const { t } = useTranslation();
  const isLoading = useRouterState({ select: (s) => s.status === 'pending' });

  const user = Api.getAuthenticatedUser();

  const handleClose = () => {
    setAnchorLanguageMenu(null);
    setAnchorUserMenu(null);
  };

  return (
    <ElevationScroll>
      <>
        <AppBar>
          <Toolbar>
            <Box sx={{ flexGrow: 1, alignItems: 'center', display: 'flex', gap: 1 }}>
              <MUILink component={Link} to="/" color="#FFF" variant="h6" underline="none">
                {t('GuestBook')}
              </MUILink>
              {isLoading && <CircularProgress size={16} thickness={10} sx={{ color: 'white' }} />}
            </Box>
            <IconButton size="large" onClick={(event) => setAnchorLanguageMenu(event.currentTarget)}>
              <Translate sx={{ color: 'white' }} />
            </IconButton>
            {user ? (
              <IconButton onClick={(event) => setAnchorUserMenu(event.currentTarget)} sx={{ p: 0 }}>
                <Avatar alt={user.username} src={`storage/${user.image}`} />
              </IconButton>
            ) : (
              <IconButton size="large" onClick={(event) => setAnchorUserMenu(event.currentTarget)} color="inherit">
                <AccountCircle />
              </IconButton>
            )}
            <LanguageMenu anchorEl={anchorLanguageMenu} handleClose={handleClose} />
            <UserMenu anchorEl={anchorUserMenu} handleClose={handleClose} />
          </Toolbar>
        </AppBar>
        <Toolbar />
      </>
    </ElevationScroll>
  );
};

export default Header;
