import { FC, useEffect, useState } from 'react';

import { IconArrowUp } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

type NewPostsButtonProps = {
  inViewMessagesEnd: boolean;
  onClick: () => void;
};

const NewPostsButton: FC<NewPostsButtonProps> = ({
  inViewMessagesEnd,
  onClick,
}) => {
  const { t } = useTranslation(['post']);
  const [newPostsButtonWidth, setNewPostsButtonWidth] = useState(0);

  const feedContainer = document.getElementById('feed-container');
  const feedContainerWidth = feedContainer?.offsetWidth || 0;
  const feedContainerOffsetLeft = feedContainer?.offsetLeft || 0;
  const paddingLeft = feedContainer
    ? Number(
        getComputedStyle(feedContainer)
          ?.getPropertyValue('padding-left')
          ?.replace('px', ''),
      )
    : 0;
  const feedContainerWidthWithoutPadding = feedContainerWidth - paddingLeft;
  const sidebarWidth = document.getElementById('sidebar')?.offsetWidth || 0;
  const navbarHeight =
    document.getElementById('dashboard-navbar')?.offsetHeight || 0;

  const fixedWidth =
    sidebarWidth +
    paddingLeft +
    feedContainerOffsetLeft +
    feedContainerWidthWithoutPadding / 2 -
    newPostsButtonWidth / 2;
  const absoluteWidth =
    paddingLeft +
    feedContainerWidthWithoutPadding / 2 -
    newPostsButtonWidth / 2;

  useEffect(() => {
    const newPostsButtonWidthAux =
      document.getElementById('new-posts-button')?.offsetWidth || 0;
    setNewPostsButtonWidth(newPostsButtonWidthAux);
  }, []);

  return (
    <Button
      id="new-posts-button"
      variant="contained"
      sx={{
        position: inViewMessagesEnd ? 'absolute' : 'fixed',
        left: inViewMessagesEnd ? `${absoluteWidth}px` : `${fixedWidth}px`,
        top: inViewMessagesEnd ? 'auto' : `${navbarHeight + 16}px`,
        zIndex: 4,
        mt: -1,
        visibility: newPostsButtonWidth === 0 ? 'hidden' : 'visible',
        borderRadius: 4,
      }}
      onClick={onClick}
    >
      {t('post:new_posts')}
      <Stack sx={{ ml: 0.5, alignItems: 'flex-start' }}>
        <IconArrowUp size="15" />
      </Stack>
    </Button>
  );
};

export default NewPostsButton;
