import { useTranslation } from 'react-i18next';

import { type LibrariesSidebarProps } from '@composed-components/LibrariesSidebar';
import { SidebarSortButtons } from '@composed-components/LibrariesSidebar/components/headers/SidebarSortButtons';
import { SidebarHeaderLoading } from '@composed-components/LibrariesSidebar/components/loading/SidebarHeaderLoading';
import { useSidebarContext } from '@composed-components/LibrariesSidebar/context';
import Tooltip from '@design-system/Tooltip';
import { IconButton, Stack, Typography, useTheme } from '@mui/material';
import { IconMenuOrder, IconPlus } from '@tabler/icons-react';

type SidebarHeaderActionsProps = Pick<
  LibrariesSidebarProps,
  'loading' | 'slotProps' | 'parentId' | 'onAdd'
> & { title?: string; isEmpty?: boolean };

export const SidebarHeaderActions = ({
  title,
  parentId,
  isEmpty,
  onAdd,
  loading,
  slotProps,
}: SidebarHeaderActionsProps) => {
  const { palette } = useTheme();
  const { t } = useTranslation('material_hu_only');
  const { handleToggleSortMode, showSortButton, isSortMode } =
    useSidebarContext();

  if (loading) return <SidebarHeaderLoading />;

  const formattedTitle = isSortMode ? t('libraries_sidebar.reorder') : title;
  const addButtonTooltipTitle = parentId
    ? t('libraries_sidebar.add_subarticle')
    : t('libraries_sidebar.add_article');

  return (
    <Stack
      className="sidebar-header-actions"
      sx={{
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexShrink: 0,
        py: 1.5,
        minHeight: 64,
        pl: 2,
        pr: 1,
        position: 'relative',
        backgroundColor: palette.new.background.elements.default,
      }}
    >
      <Typography
        variant="globalM"
        fontWeight="fontWeightSemiBold"
      >
        {formattedTitle}
      </Typography>
      <SidebarSortButtons loading={loading} />
      <Stack sx={{ flexDirection: 'row', gap: 1 }}>
        {showSortButton && !isEmpty && (
          <Tooltip
            title={
              slotProps?.sortButton?.tooltipTitle ||
              t('libraries_sidebar.reorder')
            }
            direction="bottom"
          >
            <IconButton
              aria-label={
                slotProps?.sortButton?.label || t('libraries_sidebar.reorder')
              }
              onClick={handleToggleSortMode}
            >
              <IconMenuOrder />
            </IconButton>
          </Tooltip>
        )}
        {onAdd && (
          <Tooltip
            title={slotProps?.addButton?.tooltipTitle || addButtonTooltipTitle}
            direction="bottom"
          >
            <IconButton
              aria-label={slotProps?.addButton?.label || addButtonTooltipTitle}
              onClick={() => onAdd?.(parentId)}
            >
              <IconPlus />
            </IconButton>
          </Tooltip>
        )}
      </Stack>
    </Stack>
  );
};
