import { type FC, Fragment, useMemo } from 'react';

import { IconChecks, IconPoint } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Popover, { type PopoverOrigin } from '@material-hu/mui/Popover';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { useAuth } from 'src/contexts/JWTContext';
import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import { type MemberReadMessage } from 'src/pages/dashboard/Conversations/types';
import { formateDateForMessageRead } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getInitials } from 'src/utils/userUtils';

import { useGetMembersReadMessages } from '../../hooks/useConversationsQueries';
import LazySecureImage from '../shared/LazySecureImage';
import ThreadInfiniteList from '../shared/ThreadInfiniteList';

type MessageInfoProps = {
  open: boolean;
  onClose: () => void;
  channel: string;
  messageTs: string;
  totalMembers: number;
};

const POPOVER_HEIGHT = 350;
const MARGIN_THRESHOLD = 16;
const POPOVER_GAP = 8;

const getPopoverPosition = (bubbleId: string) => {
  const bubbleElement = document.getElementById(bubbleId);
  if (!bubbleElement) return null;

  const bubbleRect = bubbleElement.getBoundingClientRect();
  const spaceBelow = window.innerHeight - bubbleRect.bottom - MARGIN_THRESHOLD;
  const spaceAbove = bubbleRect.top - MARGIN_THRESHOLD;
  const openUpward = spaceBelow < POPOVER_HEIGHT && spaceAbove > spaceBelow;

  return {
    position: {
      top: openUpward
        ? bubbleRect.top - POPOVER_GAP
        : bubbleRect.bottom + POPOVER_GAP,
      left: bubbleRect.right,
    },
    origin: {
      anchor: {
        vertical: openUpward ? 'top' : 'bottom',
        horizontal: 'right',
      } as PopoverOrigin,
      transform: {
        vertical: openUpward ? 'bottom' : 'top',
        horizontal: 'right',
      } as PopoverOrigin,
    },
  };
};

const MessageInfo: FC<MessageInfoProps> = props => {
  const { open, onClose, channel, messageTs, totalMembers } = props;

  const { user } = useAuth();
  const { t } = useLokaliseTranslation(['chat']);
  const theme = useTheme();
  const {
    members,
    isLoading,
    isSuccess,
    isEmpty,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
  } = useGetMembersReadMessages({
    channelId: channel,
    messageTs,
    enabled: open,
  });

  const popoverConfig = useMemo(() => {
    if (!open) return null;
    return getPopoverPosition(messageTs);
  }, [open, messageTs]);

  return (
    <Popover
      open={open && !!popoverConfig}
      anchorReference="anchorPosition"
      anchorPosition={popoverConfig?.position}
      onClose={onClose}
      anchorOrigin={popoverConfig?.origin.anchor}
      transformOrigin={popoverConfig?.origin.transform}
      slotProps={{
        paper: {
          sx: {
            overflowY: 'hidden',
          },
        },
      }}
      marginThreshold={MARGIN_THRESHOLD}
    >
      <Stack
        sx={{ m: 2, flexDirection: 'row', alignItems: 'center', gap: 0.5 }}
      >
        <IconChecks
          size={16}
          color={theme.palette.new.graphics.brand[400]}
        />
        <Typography
          variant="globalXS"
          fontWeight="fontWeightSemiBold"
        >
          {t('message_info.read_by')}
        </Typography>
      </Stack>
      <HuCardContainer
        sx={{
          m: 2,
          '& .MuiCardContent-root': { p: 0, mx: 0 },
          maxWidth: 400,
          minWidth: 360,
          maxHeight: 300,
          overflowY: 'auto',
          '::-webkit-scrollbar': {
            width: '6px',
          },
          '::-webkit-scrollbar-track': {
            background: theme.palette.new.background.elements.grey,
            borderRadius: '3px',
          },
          '::-webkit-scrollbar-thumb': {
            background: theme.palette.new.text.neutral.disabled,
            borderRadius: '3px',
            '&:hover': {
              background: theme.palette.new.text.neutral.lighter,
            },
          },

          scrollbarWidth: 'thin',
          scrollbarColor: `${theme.palette.new.text.neutral.disabled} ${theme.palette.new.background.elements.grey}`,
        }}
      >
        <ThreadInfiniteList
          isSuccess={isSuccess}
          isEmpty={isEmpty}
          hasNextPage={hasNextPage || false}
          renderSkeleton={
            <Stack
              sx={{
                flexDirection: 'row',
                gap: 1,
                alignItems: 'center',
                px: 2,
                pt: 1,
                pb: 2,
              }}
            >
              <Skeleton
                variant="rectangular"
                width="100%"
                height={24}
              />
            </Stack>
          }
          isLoading={isLoading}
          listWrapperProps={{
            hasNextPage: hasNextPage || false,
            fetchNextPage,
            isFetchingNextPage,
          }}
        >
          {members.map((member: MemberReadMessage, index: number) => {
            const messageReadDate = formateDateForMessageRead(
              member.read_at,
              user,
              t,
            );
            return (
              <Fragment key={member.id}>
                <Stack
                  sx={{
                    px: 1,
                    py: 1.5,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}
                >
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      gap: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <LazySecureImage
                      url={member.pictureUrl || ''}
                      isAvatar
                      imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
                      avatarProps={{
                        text: getInitials(member.userName || ''),
                      }}
                    />
                    <Typography
                      variant="globalXS"
                      fontWeight="fontWeightSemiBold"
                      sx={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        display: '-webkit-box',
                        WebkitLineClamp: 1,
                        WebkitBoxOrient: 'vertical',
                        maxWidth: 180,
                      }}
                    >
                      {member.userName}
                    </Typography>
                  </Stack>
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      gap: 0.5,
                      alignItems: 'center',
                    }}
                  >
                    <Typography
                      variant="globalXXS"
                      sx={{
                        whiteSpace: 'nowrap',
                        color: theme.palette.new.text.neutral.lighter,
                      }}
                    >
                      {messageReadDate?.date}
                    </Typography>
                    <Typography
                      variant="globalXXS"
                      sx={{
                        whiteSpace: 'nowrap',
                        color: theme.palette.new.text.neutral.default,
                      }}
                    >
                      {messageReadDate?.hour}
                    </Typography>
                  </Stack>
                </Stack>
                {index < members.length - 1 && <Divider />}
              </Fragment>
            );
          })}
          {!!members.length && <Divider />}
          {!isLoading && members.length < totalMembers && (
            <Stack
              sx={{ flexDirection: 'row', justifyContent: 'center', my: 2 }}
            >
              <IconPoint />
              <IconPoint />
              <IconPoint />
            </Stack>
          )}
        </ThreadInfiniteList>
      </HuCardContainer>
    </Popover>
  );
};

export default MessageInfo;
