import { FC, MouseEvent } from 'react';

import { IconEdit } from '@material-hu/icons/tabler';

import Accordion, {
  AccordionProps,
} from '@material-hu/components/design-system/Accordion';
import { Poll, PollStatus, StreamStatus } from 'src/types/stream';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { getPollStatus } from '../../../utils';

import PollItemDetail from './ItemDetail';

type ItemProps = {
  streamId: string;
  poll: Poll;
  streamStatus: StreamStatus;
  isAnotherPollActive: boolean;
  onEditButtonClick: (poll: Poll) => void;
};

const Item: FC<ItemProps> = props => {
  const {
    streamId,
    poll,
    streamStatus,
    isAnotherPollActive,
    onEditButtonClick,
  } = props;
  const { t } = useLokaliseTranslation('livestream');

  const { startsAt, endsAt } = poll.pollConfiguration;
  const pollStatus = getPollStatus(startsAt, endsAt);

  const handleEditButtonClick = (event: MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    onEditButtonClick(poll);
  };

  const accordionPropsByPollStatus: Record<
    PollStatus,
    Pick<AccordionProps, 'description' | 'pill' | 'action'>
  > = {
    [PollStatus.IDLE]: {
      description: t('polls.no_votes'),
      pill: {
        label: t('polls.not_started'),
        type: 'warning',
        size: 'small',
        hasIcon: false,
      },
      action: {
        onClick: handleEditButtonClick,
        children: <IconEdit />,
      },
    },
    [PollStatus.ACTIVE]: {
      description: t('polls.votes_count', { count: poll.totalAnswerCount }),
      pill: {
        label: t('polls.active'),
        type: 'success',
        size: 'small',
        hasIcon: false,
      },
    },
    [PollStatus.ENDED]: {
      description: t('polls.votes_count', { count: poll.totalAnswerCount }),
      pill: {
        label: t('polls.finished'),
        type: 'neutral',
        size: 'small',
        hasIcon: false,
      },
    },
  };

  return (
    <Accordion
      {...accordionPropsByPollStatus[pollStatus]}
      title={poll.title || ''}
      elevation={0}
      customDetail={
        <PollItemDetail
          streamId={streamId}
          poll={poll}
          streamStatus={streamStatus}
          isAnotherPollActive={isAnotherPollActive}
        />
      }
      withTitleEllipsis
      sx={{
        border: theme =>
          `1px solid ${theme.palette.new.border.neutral.default}`,
        borderRadius: theme => theme.shape.borderRadiusL,
        '&:first-of-type': {
          borderTopLeftRadius: '16px',
          borderTopRightRadius: '16px',
        },
        '&:last-of-type': {
          borderBottomLeftRadius: '16px',
          borderBottomRightRadius: '16px',
        },
      }}
    />
  );
};

export default Item;
