import { type FC, memo, useCallback, useRef, useState } from 'react';

import axios, { type AxiosResponse } from 'axios';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import Box from '@material-hu/mui/Box';
import Typography from '@material-hu/mui/Typography';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type GetViewersFunction } from 'src/hooks/usePostViewers';
import { type PostViewer } from 'src/types/posts';
import { type CursorPagination } from 'src/types/services';
import { ButtonText } from 'src/pages/dashboard/feed/components/ButtonText';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import getViewersListDrawer from './ViewersListDrawer';
import ViewerTooltip from './ViewerTooltip';

export type PostCardViewersInlineProps = {
  postId: number;
  viewerCount: number;
  getViewers: GetViewersFunction;
  disabled?: boolean;
  containerRef?: React.RefObject<HTMLDivElement>;
};

export const PostCardViewersInline: FC<PostCardViewersInlineProps> = ({
  postId,
  viewerCount,
  getViewers,
  disabled = false,
  containerRef: externalContainerRef,
}) => {
  const { t } = useTranslation('post');
  const HugoThemeProvider = useHuGoTheme();
  const internalContainerRef = useRef<HTMLDivElement>(null);
  const containerRef = externalContainerRef || internalContainerRef;

  const [fetchedCount, setFetchedCount] = useState<number | undefined>();
  const [isViewersForbidden, setIsViewersForbidden] = useState<boolean>(false);
  const displayCount = fetchedCount ?? viewerCount;

  const handleViewerCountUpdate = useCallback((count: number) => {
    setFetchedCount(prev =>
      prev === undefined ? count : Math.max(prev, count),
    );
  }, []);

  const getSafeViewers: GetViewersFunction = useCallback(
    async params => {
      try {
        return await getViewers(params);
      } catch (error) {
        if (axios.isAxiosError(error) && error.response?.status === 403) {
          setIsViewersForbidden(true);
          return {
            data: {
              items: [],
              cursor: null,
            },
            status: 200,
            statusText: 'OK',
            headers: {},
            config: {} as AxiosResponse<
              CursorPagination<PostViewer[]>
            >['config'],
          };
        }
        throw error;
      }
    },
    [getViewers],
  );

  const extraProps = {
    postId,
    getViewers: getSafeViewers,
    container: containerRef.current,
    onViewerCountUpdate: handleViewerCountUpdate,
  };

  const { drawer, showDrawer } = useDrawerV2(args =>
    getViewersListDrawer({ ...args, ...extraProps }),
  );

  if (isViewersForbidden || displayCount <= 0) {
    return null;
  }

  return (
    <HugoThemeProvider>
      <Box ref={containerRef}>
        {drawer}
        <ViewerTooltip
          postId={postId}
          viewerCount={displayCount}
          getViewers={getSafeViewers}
          onViewerCountUpdate={handleViewerCountUpdate}
          popperProps={{
            container: containerRef.current,
          }}
        >
          <ButtonText
            variant="tertiary"
            disabled={disabled}
            onClick={showDrawer}
            sx={{
              cursor: 'pointer',
              '&:hover': {
                '& .MuiTypography-root': {
                  textDecoration: 'underline',
                  textDecorationColor: theme =>
                    theme.palette.new.text.neutral.lighter,
                },
              },
            }}
          >
            <Typography
              variant="globalXS"
              fontWeight="fontWeightSemiBold"
              sx={{
                color: theme => theme.palette.new.text.neutral.lighter,
              }}
            >
              {t('seen_by_count', { count: displayCount })}
            </Typography>
          </ButtonText>
        </ViewerTooltip>
      </Box>
    </HugoThemeProvider>
  );
};

export default memo(PostCardViewersInline);
