import { type FC } from 'react';

import CardHeader from '@material-hu/mui/CardHeader';
import Typography from '@material-hu/mui/Typography';

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

import { useAuth } from 'src/contexts/JWTContext';
import { type SegmentationMapValues } from 'src/types/segmentation';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { useSegmentationDrawer } from 'src/components/segmentations/useSegmentationDrawer';
import ProfilePicture from 'src/components/user/ProfilePicture';

const EMPTY_SEGMENTATION_MAP = new Map<number, SegmentationMapValues[]>();

export type LoggedUserAvatarProps =
  | {
      selectedItems: Map<number, SegmentationMapValues[]>;
      onChange?: (items: Map<number, SegmentationMapValues[]>) => void;
      hasItemsSegmetated: boolean;
      showSegmentate: boolean;
      labelOverride?: string;
      showPill?: true;
    }
  | {
      selectedItems?: never;
      onChange?: never;
      hasItemsSegmetated?: never;
      showSegmentate?: never;
      labelOverride?: never;
      showPill?: false;
    };

const LoggedUserAvatar: FC<LoggedUserAvatarProps> = props => {
  const {
    selectedItems,
    onChange,
    hasItemsSegmetated,
    showSegmentate,
    labelOverride,
    showPill = true,
  } = props;

  const { t } = useTranslation();
  const { user } = useAuth();

  const { drawer, showDrawer } = useSegmentationDrawer({
    selectedItems: selectedItems ?? EMPTY_SEGMENTATION_MAP,
    onSubmit: onChange,
  });

  if (!user) {
    return null;
  }

  return (
    <>
      <CardHeader
        sx={{
          px: 0,
          pt: 0,
          '& .MuiCardHeader-avatar': {
            mr: 1,
          },
        }}
        avatar={
          <ProfilePicture
            id={user.id}
            user={user}
            sx={{ width: '40px', height: '40px' }}
            withLink
          />
        }
        title={
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
            sx={{ mb: 0.5 }}
          >
            {getFullName(user)}
          </Typography>
        }
        subheader={
          showPill ? (
            <HuPills
              disabled={!showSegmentate}
              onClick={showSegmentate ? () => showDrawer({}) : undefined}
              label={
                labelOverride ??
                (hasItemsSegmetated
                  ? t('post:personalized')
                  : t('post:all_the_company'))
              }
              type={showSegmentate ? 'info' : 'disabled'}
              hasIcon={false}
              size="small"
            />
          ) : null
        }
      />
      {showPill && drawer}
    </>
  );
};

export default LoggedUserAvatar;
