import { Fragment } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Typography, { type TypographyProps } from '@material-hu/mui/Typography';
import { getConfettiColor } from '@material-hu/utils/colors';

import Button from '@material-hu/components/design-system/Buttons/Button';
import Pills from '@material-hu/components/design-system/Pills';

import { type Acknowledgement } from 'src/pages/dashboard/acknowledgements/types';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { MAX_CATEGORY_NAME_LENGTH, USERS_AVATARS_LIMIT } from '../../constants';

import AcknowledgementAvatars from './AcknowledgementAvatars';
import getAcknowledgedsProfileDrawer from './getAcknowledgedsProfileDrawer';

type AcknowledgementProfilesProps = Pick<
  Acknowledgement,
  'acknowledgeds' | 'category'
>;

const textStyle: TypographyProps = {
  variant: 'globalM',
  fontWeight: 'fontWeightSemiBold',
  alignSelf: 'center',
};

const AcknowledgementProfiles = ({
  acknowledgeds = [],
  category,
}: AcknowledgementProfilesProps) => {
  const { t } = useLokaliseTranslation('acknowledgements');
  const slicedAcknowledgeds =
    acknowledgeds?.slice(0, USERS_AVATARS_LIMIT) || [];

  const {
    showDrawer: showAcknowledgedsNamesDrawer,
    drawer: acknowledgedsNamesDrawer,
  } = useDrawerV2(args =>
    getAcknowledgedsProfileDrawer({ ...args, acknowledgeds, category }),
  );

  const handleOpenAcknowledgedsNamesDrawer = () =>
    showAcknowledgedsNamesDrawer({});

  const userExceedsLimit =
    acknowledgeds && acknowledgeds.length > USERS_AVATARS_LIMIT;

  const hasComma = (index: number) => {
    const isLastUser = index === slicedAcknowledgeds.length - 1;
    const isSecondLastUser = index === slicedAcknowledgeds.length - 2;

    if (userExceedsLimit) return !isLastUser;

    return !isLastUser && !isSecondLastUser;
  };

  const hasAndConnector = (index: number) => {
    const moreThanOneUser = acknowledgeds && acknowledgeds.length > 1;

    return (
      moreThanOneUser &&
      index === slicedAcknowledgeds.length - (userExceedsLimit ? 0 : 1)
    );
  };

  const confettiColor = getConfettiColor(category.color).confettiColor;

  return (
    <Stack sx={{ width: '100%', pt: 2, pb: 3, gap: 2 }}>
      <AcknowledgementAvatars
        showAcknowledgedsNamesDrawer={handleOpenAcknowledgedsNamesDrawer}
        acknowledgeds={acknowledgeds}
      />
      {acknowledgedsNamesDrawer}
      <Stack
        sx={{
          flexDirection: 'row',
          flexWrap: 'wrap',
          justifyContent: 'center',
        }}
      >
        {slicedAcknowledgeds.map((user, index) => {
          return (
            <Fragment key={user.id}>
              <Link
                component={!user.deleted ? RouterLink : 'span'}
                to={!user.deleted ? profileRoutes.profile(user.id) : undefined}
                sx={{ textDecoration: 'none', mr: 0.5 }}
              >
                {hasAndConnector(index) && (
                  <Typography
                    {...textStyle}
                    sx={{ mr: 0.5 }}
                  >
                    {t('general:and')}
                  </Typography>
                )}
                <Typography {...textStyle}>{getFullName(user)}</Typography>
                {hasComma(index) && (
                  <Typography {...textStyle}>{','}</Typography>
                )}
              </Link>
            </Fragment>
          );
        })}
        {acknowledgeds && acknowledgeds.length > USERS_AVATARS_LIMIT && (
          <>
            <Typography
              {...textStyle}
              sx={{ mx: 0.5 }}
            >
              {t('general:and')}
            </Typography>
            <Button
              variant="text"
              onClick={handleOpenAcknowledgedsNamesDrawer}
              sx={{
                p: 0,
                px: 0.5,
                height: 'unset',
                '&:hover': { backgroundColor: 'transparent' },
              }}
            >
              <Typography
                {...textStyle}
                sx={{ color: theme => theme.palette.primary.main }}
              >
                {t('more_acknowledgeds', {
                  count: acknowledgeds.length - USERS_AVATARS_LIMIT,
                })}
              </Typography>
            </Button>
          </>
        )}
      </Stack>
      {category.name.length > MAX_CATEGORY_NAME_LENGTH ? (
        <Typography
          variant="globalXS"
          fontWeight="fontWeightSemiBold"
          sx={{ textAlign: 'center' }}
        >
          {category.name}
        </Typography>
      ) : (
        <Pills
          sx={{
            maxWidth: 'fit-content',
            alignSelf: 'center',
            backgroundColor: category.color,
            borderColor: confettiColor,
            '& span': { color: confettiColor },
          }}
          label={category.name}
          hasIcon={false}
        />
      )}
    </Stack>
  );
};

export default AcknowledgementProfiles;
