import { type FieldValues } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import Alert from '@design-system/Alert';
import { useDebouncedFormValues } from '@hooks/useDebouncedFormValues';

import useSelectedCollaboratorsDrawer from '../useSelectedCollaboratorsDrawer';

import { type CriteriaCollaboratorsReachConfig } from './types';

type CriteriaCollaboratorsReachFooterProps<TValues extends FieldValues> = {
  collaboratorsReach: CriteriaCollaboratorsReachConfig<TValues>;
  onSelectedCollaboratorsDismiss?: () => void;
};

const CriteriaCollaboratorsReachFooter = <TValues extends FieldValues>({
  collaboratorsReach,
  onSelectedCollaboratorsDismiss,
}: CriteriaCollaboratorsReachFooterProps<TValues>) => {
  const { t } = useTranslation('material_hu_only');
  const formValues = useDebouncedFormValues<TValues>();

  const { selectedCollaboratorsDrawer, showSelectedCollaboratorsDrawer } =
    useSelectedCollaboratorsDrawer();

  const { isFormEmpty, onViewCollaborators, queryKey, useCount, useService } =
    collaboratorsReach;

  const { count, loading } = useCount(formValues);
  const service = useService(formValues);

  const isEmpty = isFormEmpty(formValues);

  const handleViewCollaborators = () => {
    onViewCollaborators?.();
    showSelectedCollaboratorsDrawer({
      service,
      queryKey,
      totalCount: count,
      onDismiss: onSelectedCollaboratorsDismiss,
    });
  };

  const renderAlert = () => {
    if (isEmpty) {
      return (
        <Alert
          severity="info"
          title={t('audience.no_collaborators_selected')}
        />
      );
    }

    if (loading) {
      return (
        <Alert
          severity="info"
          title=""
          loading
        />
      );
    }

    return (
      <Alert
        severity="info"
        title={t('audience.total_collaborators', { count })}
        action={{
          text: t('audience.view_collaborators'),
          onClick: handleViewCollaborators,
        }}
      />
    );
  };

  return (
    <>
      {renderAlert()}
      {selectedCollaboratorsDrawer}
    </>
  );
};

export default CriteriaCollaboratorsReachFooter;
