import { forwardRef, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';

import {
  AppBar,
  Button,
  ButtonBase,
  type ButtonProps,
  IconButton,
  Popover,
  Stack,
  Toolbar,
  useTheme,
} from '@mui/material';
import { IconBell, IconHelp, IconMenu2, IconWorld } from '@tabler/icons-react';
import { isNil } from 'lodash';

import Avatar from '../../Avatar';
import Badge from '../../Badge';
import Pills from '../../Pills';

import { type HomeHeaderProps } from './types';

const POPOVER_ANCHOR_ORIGIN = {
  vertical: 'bottom' as const,
  horizontal: 'right' as const,
};
const POPOVER_TRANSFORM_ORIGIN = {
  vertical: 'top' as const,
  horizontal: 'right' as const,
};

const HomeHeader = forwardRef<HTMLDivElement, HomeHeaderProps>(
  (
    {
      onOpenMenu,
      logoSrc,
      logoAlt,
      isAdmin = false,
      extraOptions,
      avatarProps,
      notificationsCount = 0,
      avatarButtonProps,
      avatarPopoverContent,
      hideSupportButton = false,
      onOpenLanguageMenu,
      hideLanguageButton = false,
      onOpenSupportMenu,
      hideNotificationsButton = false,
      sx,
      logoLink = '/',
      hideMenuButton = false,
      supportButtonProps,
      onOpenNotificationsMenu,
      id,
      disabledMenuButton = false,
      banner,
      centerContent,
      hasUnreadNotifications = false,
      onOpenAvatarMenu,
      avatarPopoverOpen,
      onAvatarPopoverOpenChange,
    },
    ref,
  ) => {
    const theme = useTheme();
    const { t } = useTranslation('material_hu_only');

    const [internalAvatarAnchor, setInternalAvatarAnchor] =
      useState<HTMLButtonElement | null>(null);

    const isControlled = !isNil(avatarPopoverOpen);
    const avatarAnchorEl =
      !isControlled || avatarPopoverOpen ? internalAvatarAnchor : null;

    const handleOpenAvatarMenu = useCallback(
      (event: React.MouseEvent<HTMLButtonElement>) => {
        onOpenAvatarMenu?.(event);
        setInternalAvatarAnchor(event.currentTarget);
        if (isControlled) {
          onAvatarPopoverOpenChange?.(true);
        }
      },
      [isControlled, onOpenAvatarMenu, onAvatarPopoverOpenChange],
    );

    const handleCloseAvatarMenu = useCallback(() => {
      setInternalAvatarAnchor(null);
      if (isControlled) {
        onAvatarPopoverOpenChange?.(false);
      }
    }, [isControlled, onAvatarPopoverOpenChange]);

    const notificationsIconSx = useMemo(
      () =>
        hasUnreadNotifications
          ? {
              '& .MuiBadge-root svg': {
                transform: 'rotate(45deg)',
                transition: 'transform 200ms ease',
              },
            }
          : undefined,
      [hasUnreadNotifications],
    );

    return (
      <AppBar
        id={id}
        ref={ref}
        elevation={0}
        sx={{
          backgroundColor: theme.palette.new.background.layout.tertiary,
          borderBottom: `1px solid ${theme.palette.new.border.neutral.default}`,
          ...sx,
        }}
      >
        {banner}
        <Toolbar sx={{ px: `${theme.spacing(2)} !important`, py: 1.5, gap: 2 }}>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
            {!hideMenuButton && (
              <IconButton
                onClick={onOpenMenu}
                disabled={disabledMenuButton}
              >
                <IconMenu2 />
              </IconButton>
            )}
            <Link to={logoLink}>
              <Stack
                sx={{
                  height: '48px',
                  maxWidth: '140px',
                  p: 0.25,
                  boxSizing: 'border-box',
                }}
              >
                <img
                  src={logoSrc}
                  alt={logoAlt}
                  style={{
                    height: '100%',
                    objectFit: 'contain',
                  }}
                />
              </Stack>
            </Link>
            {isAdmin && (
              <Pills
                label={t('hu_header.admin')}
                type="highlight"
                hasIcon={false}
                size="small"
              />
            )}
          </Stack>
          {centerContent && (
            <Stack
              sx={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                minWidth: 0,
              }}
            >
              {centerContent}
            </Stack>
          )}

          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
              ml: centerContent ? 0 : 'auto',
            }}
          >
            {extraOptions?.map(({ key, ...buttonProps }) => (
              <Button
                key={key}
                variant="outlined"
                {...(buttonProps as ButtonProps)}
              />
            ))}
            {!hideSupportButton && !onOpenSupportMenu && (
              <IconButton
                target="_blank"
                {...supportButtonProps}
              >
                <IconHelp color={theme.palette.new.text.neutral.default} />
              </IconButton>
            )}
            {onOpenSupportMenu && (
              <IconButton
                onClick={onOpenSupportMenu}
                aria-label={t('hu_header.open_support_menu')}
              >
                <IconHelp color={theme.palette.new.text.neutral.default} />
              </IconButton>
            )}
            {!hideLanguageButton && !!onOpenLanguageMenu && (
              <IconButton onClick={onOpenLanguageMenu}>
                <IconWorld color={theme.palette.new.text.neutral.default} />
              </IconButton>
            )}
            {!hideNotificationsButton && (
              <IconButton
                onClick={onOpenNotificationsMenu}
                sx={notificationsIconSx}
              >
                <Badge
                  badgeContent={notificationsCount}
                  color="primary"
                >
                  <IconBell color={theme.palette.new.text.neutral.default} />
                </Badge>
              </IconButton>
            )}
            <ButtonBase
              onClick={handleOpenAvatarMenu}
              {...avatarButtonProps}
              disableRipple
            >
              <Avatar {...avatarProps} />
            </ButtonBase>
            <Popover
              anchorEl={avatarAnchorEl}
              anchorOrigin={POPOVER_ANCHOR_ORIGIN}
              transformOrigin={POPOVER_TRANSFORM_ORIGIN}
              slotProps={{
                paper: {
                  sx: {
                    borderRadius: theme.shape.borderRadiusL,
                    boxShadow: theme.shadows[2],
                  },
                },
              }}
              onClose={handleCloseAvatarMenu}
              open={
                isControlled ? Boolean(avatarPopoverOpen) : !!avatarAnchorEl
              }
              keepMounted
            >
              {avatarPopoverContent}
            </Popover>
          </Stack>
        </Toolbar>
      </AppBar>
    );
  },
);

HomeHeader.displayName = 'HomeHeader';

export type { HomeHeaderProps };

export default HomeHeader;
