import { useMemo, useState } from 'react';
import { useParams } from 'react-router';

import Stack from '@material-hu/mui/Stack';

import HuMenu from '@material-hu/components/design-system/Menu';

import { useAuth } from 'src/contexts/JWTContext';
import { type MessageReaction } from 'src/pages/dashboard/Conversations/types';
import { useReactionsWithUsers } from 'src/pages/dashboard/Conversations/hooks/useReactionsWithUsers';
import { buildReactionUsersMap } from 'src/pages/dashboard/Conversations/utils';

import { useGetReactions } from '../../../../hooks/useConversationsQueries';
import ReactionsTabs from '../ReactionsTabs';

import ReactionItem from './ReactionItem';

type ReactionsListProps = {
  anchorEl: HTMLElement | null;
  open: boolean;
  onClose: () => void;
  channel: string;
  ts: string;
  reactionsFromMessage: MessageReaction[];
};

const ReactionsList = ({
  anchorEl,
  open,
  onClose,
  channel,
  ts,
  reactionsFromMessage,
}: ReactionsListProps) => {
  const { id } = useParams();
  const { user: loggedUser } = useAuth();
  const { data: reactions } = useGetReactions({
    channel,
    ts,
    isOpen: open,
    initialData: reactionsFromMessage,
  });
  const [selectedTab, setSelectedTab] = useState(0);

  const reactionsWithUsers = useReactionsWithUsers(reactions, id);

  const usersMap = useMemo(
    () => buildReactionUsersMap(reactionsWithUsers, loggedUser?.id),
    [reactionsWithUsers, loggedUser?.id],
  );

  const currentReaction = reactions[selectedTab]?.name || '';
  const filteredUsers = usersMap.get(currentReaction) || [];

  return (
    <HuMenu
      id="reactions-list-menu"
      open={open}
      onClose={onClose}
      anchorEl={anchorEl}
      position="left"
      sx={{
        '& .MuiDivider-root': {
          display: 'none',
        },
        '& .MuiPaper-root': {
          minWidth: '540px',
        },
        '& .MuiList-root': {
          overflowY: 'auto',
          minWidth: '540px',
          height: '400px',
          msOverflowStyle: 'none' /* IE and Edge */,
          scrollbarWidth: 'none' /* Firefox */,
          '&::-webkit-scrollbar': {
            display: 'none' /* Chrome, Safari and Opera */,
          },
        },
      }}
      header={
        <Stack
          sx={{
            px: 2,
            py: 0,
          }}
        >
          <ReactionsTabs
            reactions={reactions}
            selectedTab={selectedTab}
            onTabChange={setSelectedTab}
          />
        </Stack>
      }
    >
      {filteredUsers.map(user => (
        <ReactionItem
          key={`${user.id}-${user.emoji}`}
          user={user}
        />
      ))}
    </HuMenu>
  );
};

export default ReactionsList;
