import { useMemo } from 'react';

import useSelectedCollaboratorsDrawer from '@material-hu/components/composed-components/audience/hooks/useSelectedCollaboratorsDrawer';
import {
  type AudienceQuery,
  type SegmentationExpressionPayload,
} from '@material-hu/components/composed-components/audience/types';
import { audienceQueryToSegmentationExpression } from '@material-hu/components/composed-components/audience/utils';
import Alert from '@material-hu/components/design-system/Alert';

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

import useGetAudienceCount from '../hooks/useGetAudienceCount';
import { librariesKeys } from '../queries';
import { getCollaboratorsService } from '../utils';

type ArticleAudienceListAlertProps = {
  articleId: number;
  titleKey: string;
  audiencesQuery: AudienceQuery;
};

export const ArticleAudienceListAlert = ({
  audiencesQuery,
  articleId,
  titleKey,
}: ArticleAudienceListAlertProps) => {
  const { t } = useLokaliseTranslation('libraries');

  const expression: SegmentationExpressionPayload | null = useMemo(
    () => audienceQueryToSegmentationExpression(audiencesQuery),
    [audiencesQuery],
  );

  const { data: audienceCount = 0, isLoading: isCountLoading } =
    useGetAudienceCount(expression, articleId);

  const { selectedCollaboratorsDrawer, showSelectedCollaboratorsDrawer } =
    useSelectedCollaboratorsDrawer();

  const handleOpenSelectedCollaboratorsDrawer = () => {
    showSelectedCollaboratorsDrawer({
      queryKey: `${librariesKeys.audience.selectedCollaborators().join(', ')}-${articleId}`,
      totalCount: audienceCount,
      service: expression ? getCollaboratorsService(expression) : undefined,
    });
  };

  return (
    <>
      {selectedCollaboratorsDrawer}
      <Alert
        loading={isCountLoading}
        severity="info"
        title={t(titleKey, { count: audienceCount })}
        action={{
          text: t('article.collaborators.see'),
          onClick: handleOpenSelectedCollaboratorsDrawer,
        }}
        sx={{ '& .MuiSkeleton-root': { minHeight: '36px' } }}
      />
    </>
  );
};
