import { AccountCircle, DarkModeOutlined, LightMode, Person, SettingsBrightness, 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 { useApi } from '../../api/Api';
import useGuestBookStore from '../../store/store';
import LanguageMenu from '../Menus/Language/LanguageMenu';
import ThemeMenu from '../Menus/Theme/ThemeMenu';
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 [anchorThemeMenu, setAnchorThemeMenu] = useState<null | HTMLElement>(null);

  const { t } = useTranslation();
  const isLoading = useRouterState({ select: (s) => s.status === 'pending' });
  const Api = useApi();
  const [theme] = useGuestBookStore((state) => [state.theme, state.setTheme]);

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

  return (
    <ElevationScroll>
      <>
        <AppBar>
          <Toolbar>
            <Box sx={{ flexGrow: 1, alignItems: 'center', display: 'flex', gap: 1 }}>
              <MUILink component={Link} to="/" color="white" 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>
              <IconButton size="large" onClick={(event) => setAnchorThemeMenu(event.currentTarget)}>
                {theme === 'dark' && <DarkModeOutlined />}
                {theme === 'light' && <LightMode sx={{ color: 'white' }} />}
                {!theme && <SettingsBrightness sx={{ color: 'white' }} />}
              </IconButton>
              {Api.authenticatedUser ? (
                <IconButton onClick={(event) => setAnchorUserMenu(event.currentTarget)} sx={{ p: 0 }}>
                  <Avatar alt={Api.authenticatedUser.username} src={`${Api.authenticatedUser.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} />
            <ThemeMenu anchorEl={anchorThemeMenu} handleClose={handleClose} />
          </Toolbar>
        </AppBar>
        <Toolbar />
      </>
    </ElevationScroll>
  );
};

export default Header;
