import { useTranslation } from 'react-i18next';

import { type LibrariesSidebarProps } from '@composed-components/LibrariesSidebar';
import { EASING_ENTER } from '@composed-components/LibrariesSidebar/constants';
import { useSidebarContext } from '@composed-components/LibrariesSidebar/context';
import Button from '@design-system/Buttons/Button';
import { Grow, useTheme } from '@mui/material';
import Stack from '@mui/material/Stack';

type SidebarSortButtonsProps = Pick<LibrariesSidebarProps, 'loading'>;

export const SidebarSortButtons = ({ loading }: SidebarSortButtonsProps) => {
  const { t } = useTranslation();
  const { palette } = useTheme();
  const {
    isSortMode,
    handleToggleSortMode,
    handleSaveSort,
    handleRestoreSortableItems,
  } = useSidebarContext();

  if (!isSortMode) return null;

  const handleCancel = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    event.stopPropagation();

    handleRestoreSortableItems();
    handleToggleSortMode();
  };

  const handleSave = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    event.stopPropagation();

    handleSaveSort();
  };

  return (
    <Grow
      in={isSortMode}
      timeout={300}
      easing={{ enter: EASING_ENTER }}
    >
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          position: 'absolute',
          right: 8,
          gap: 2,
          zIndex: 1,
          backgroundColor: palette.new.background.elements.default,
        }}
      >
        <Button
          variant="tertiary"
          onClick={handleCancel}
          sx={{ minWidth: 'fit-content' }}
          disabled={loading}
        >
          {t('general:cancel')}
        </Button>
        <Button
          variant="primary"
          sx={{ minWidth: 'fit-content' }}
          loading={loading}
          disabled={loading}
          onClick={handleSave}
        >
          {t('general:save')}
        </Button>
      </Stack>
    </Grow>
  );
};
