import { useTranslation } from 'react-i18next';

import Tooltip from '@design-system/Tooltip';
import { IconButton, Stack, Typography, useTheme } from '@mui/material';
import {
  IconArrowLeft,
  IconWindowMaximize,
  IconWindowMinimize,
  IconX,
} from '@tabler/icons-react';
import { composeSx } from '@utils/components';

import { useDrawerSizeContext } from '../context';
import { type DrawerHeaderProps, DrawerSize } from '../types';

/**
 * Drawer.Header - Header section with title, back button, optional maximize (task focus) button, and close button
 */
export function DrawerHeader({
  title,
  onClose,
  onBack,
  hasBackButton = false,
  children,
  sx,
  onToggleTaskFocus,
  extraHeaderActions,
}: DrawerHeaderProps) {
  const { t } = useTranslation();
  const { size } = useDrawerSizeContext();
  const theme = useTheme();
  const newPalette = theme.palette?.new;
  const isTaskFocus = size === DrawerSize.TASK_FOCUS;

  return (
    <Stack
      sx={composeSx(
        {
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 1,
          py: 2,
          px: 3,
          borderBottom: `1px solid ${newPalette?.border.neutral.divider}`,
          color: 'inherit',
        },
        sx,
      )}
    >
      {hasBackButton && (
        <IconButton
          onClick={() => (onBack || onClose)?.('backButton')}
          sx={{ color: 'inherit' }}
        >
          <IconArrowLeft />
        </IconButton>
      )}
      <Typography
        variant="globalS"
        sx={{ fontWeight: 'semiBold', flex: 1, color: 'inherit' }}
      >
        {title}
      </Typography>
      {children}
      {extraHeaderActions}
      {onToggleTaskFocus && (
        <Tooltip
          title={
            isTaskFocus
              ? t('material_hu_only:drawer.exit_task_focus')
              : t('material_hu_only:drawer.enter_task_focus')
          }
        >
          <IconButton
            onClick={onToggleTaskFocus}
            sx={{ color: 'inherit' }}
          >
            {isTaskFocus ? <IconWindowMinimize /> : <IconWindowMaximize />}
          </IconButton>
        </Tooltip>
      )}
      <Tooltip title={t('general:close')}>
        <IconButton
          onClick={_event => {
            onClose?.('dismissButton');
          }}
          sx={{ color: 'inherit' }}
        >
          <IconX />
        </IconButton>
      </Tooltip>
    </Stack>
  );
}
