import { FC } from 'react';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import Card from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import Radio from '@material-hu/mui/Radio';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatarGroup from '@material-hu/components/design-system/AvatarGroup';

import { Poll, PollOption as PollOptionType } from 'src/types/posts';
import getInitials from 'src/utils/getInitials';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { isPollEnded } from 'src/utils/poll';

import { getPollVotersDrawerConfig } from './PollVotersDrawer';

type PollOptionProps = {
  pollOption: PollOptionType;
  checked: boolean;
  optionHasVotes: boolean;
  disabled: boolean;
  votersVisible: boolean;
  poll: Poll;
  postId: number;
  onClick?: () => void;
};

const PollOption: FC<PollOptionProps> = props => {
  const {
    pollOption,
    checked,
    optionHasVotes,
    disabled,
    votersVisible,
    poll,
    postId,
    onClick,
  } = props;

  const { t } = useTranslation();
  const { drawer: votersDrawer, showDrawer: showVotersDrawer } = useDrawerV2(
    getPollVotersDrawerConfig,
  );

  const isSelected = pollOption.isLoggedUserAnswer || checked;
  const showAvatars =
    votersVisible && pollOption.voters && pollOption.voters.length > 0;
  const answerCount = pollOption.answerCount;

  const handleClick = () => {
    if (!disabled && onClick) {
      onClick();
    }
  };

  const handleShowAllVoters = (e: React.MouseEvent) => {
    e.stopPropagation();
    showVotersDrawer({
      postId,
      pollId: poll.id,
      pollOption,
    });
  };

  const readOnly = isPollEnded(poll.pollConfiguration?.endsAt ?? null);

  const styles = {
    borderColor: 'new.border.neutral.default',
    backgroundColor: 'new.background.layout.tertiary',
    opacity: 1,
    cursor: 'pointer',
  };

  if (!readOnly && isSelected) {
    styles.borderColor = 'primary.main';
  }

  if (readOnly) {
    styles.backgroundColor = 'new.background.layout.tertiary';
    styles.opacity = 0.6;
  } else if (isSelected) {
    styles.backgroundColor = 'new.background.layout.brand';
  }

  if (disabled) {
    styles.cursor = 'default';
  }

  return (
    <>
      <Card
        onClick={handleClick}
        sx={{
          boxShadow: 'none',
          cursor: styles.cursor,
          border: '1px solid',
          borderColor: styles.borderColor,
          borderRadius: theme => theme.shape.borderRadiusL,
          px: 2,
          py: showAvatars ? 0 : 1.5,
          transition: 'all 0.2s ease-in-out',
          '&:hover': !disabled
            ? {
                borderColor: 'new.border.neutral.brand',
                boxShadow: 1,
              }
            : {},
          backgroundColor: styles.backgroundColor,
        }}
      >
        <CardContent sx={{ p: 0.5, '&:last-child': { pb: 0.5 } }}>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 1,
            }}
          >
            <Stack
              sx={{
                flex: 1,
                flexDirection: 'row',
                alignItems: 'center',
                gap: 1,
                opacity: styles.opacity,
              }}
            >
              <Radio
                checked={isSelected}
                disabled={readOnly}
                sx={{
                  p: 0,
                  cursor: readOnly ? 'default' : 'pointer',
                }}
                disableRipple={disabled}
              />

              {/* Option text */}
              <Typography
                variant="globalS"
                fontWeight={
                  isSelected ? 'fontWeightSemiBold' : 'fontWeightRegular'
                }
              >
                {pollOption.option}
              </Typography>
            </Stack>

            {/* Right side: Vote count and voters */}
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 2,
              }}
            >
              {optionHasVotes && (
                <>
                  <Typography
                    variant="globalXS"
                    color="new.text.neutral.lighter"
                  >
                    {t('post:votes_count', { count: answerCount })}
                  </Typography>
                  {showAvatars &&
                    pollOption.voters &&
                    pollOption.voters.length > 0 && (
                      <Stack
                        onClick={handleShowAllVoters}
                        sx={{ cursor: 'pointer' }}
                      >
                        <HuAvatarGroup
                          avatars={pollOption.voters.map(voter => ({
                            src: voter.profilePicture,
                            alt: `${voter.firstName} ${voter.lastName}`,
                            text: getInitials(
                              voter.firstName + ' ' + voter.lastName,
                            ),
                          }))}
                          totalAvatars={answerCount}
                          size="medium"
                        />
                      </Stack>
                    )}
                </>
              )}
            </Stack>
          </Stack>
        </CardContent>
      </Card>

      {votersDrawer}
    </>
  );
};

export default PollOption;
