import { useMemo, useState } from 'react';

import { GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';

import HuTabs from '@material-hu/components/design-system/Tabs';

import { Reaction } from 'src/types/reaction';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import ReactionUsersList, {
  GenericGetReactionUsersFunction,
} from './ReactionUsersList';

type ReactionUsersListDrawerProps = {
  id: number;
  filterReactions?: Reaction[];
  getReactionUsers: GenericGetReactionUsersFunction;
  container?: HTMLDivElement | null;
};

const getReactionUsersListDrawer: GetDrawerConfiguration<
  ReactionUsersListDrawerProps
> = ({ id, filterReactions, getReactionUsers, container }) => {
  const { t } = useTranslation('web_only');
  const [reaction, setReaction] = useState<Reaction | null>(
    filterReactions?.[0] ?? null,
  );

  const handleTabChange = (index: number) => {
    setReaction(filterReactions?.[index] ?? null);
  };

  const tabs = useMemo(() => {
    return filterReactions?.map(filterReaction => ({
      label: `${filterReaction.emoji} ${filterReaction.count}`,
      value: filterReaction.emoji,
    }));
  }, [filterReactions]);

  return {
    children: (
      <>
        <HuTabs
          tabs={tabs ?? []}
          variant="scrollable"
          scrollButtons={false}
          value={reaction?.emoji}
          onTabChange={(_, index) => handleTabChange(index)}
          sx={{
            position: 'sticky',
            top: 0,
            zIndex: 1,
            backgroundColor: theme =>
              theme.palette.new.background.layout.tertiary,
            pb: 1,
          }}
        />
        {reaction && (
          <ReactionUsersList
            id={id}
            reaction={reaction}
            getReactionUsers={getReactionUsers}
          />
        )}
      </>
    ),
    title: t('reactions.reaction_title'),
    hasCloseButton: true,
    sx: {
      '& .MuiPaper-root .MuiStack-root:nth-of-type(2)': {
        p: 0,
        pl: 3,
        py: 0,
        '& > ul > div': { p: 0 },
      },
    },
    container,
  };
};

export default getReactionUsersListDrawer;
