import { AccountCircle, Person, 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, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Api from '../../api/Api';
import { User } from '../../types/User';
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 [user, setUser] = useState<User>();

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

  useEffect(() => Api.subscribeToAuthenticatedUser((user) => setUser(user)), []);

  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>

            <Box sx={{ display: 'flex', gap: 1 }}>
              <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={`${user.image}`}>
                    <Person />
                  </Avatar>
                </IconButton>
              ) : (
                <IconButton size="large" onClick={(event) => setAnchorUserMenu(event.currentTarget)} color="inherit">
                  <AccountCircle />
                </IconButton>
              )}
            </Box>
            <LanguageMenu anchorEl={anchorLanguageMenu} handleClose={handleClose} />
            <UserMenu anchorEl={anchorUserMenu} handleClose={handleClose} />
          </Toolbar>
        </AppBar>
        <Toolbar />
      </>
    </ElevationScroll>
  );
};

export default Header;
