import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';
import { type TFunction } from 'react-i18next';

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

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

import { Step } from '../../../types';

import RowItem from './RowItem';

type Props = {
  showValidations: boolean;
};

const getLabel = (
  selectedSpecificAgents: boolean,
  selectedAgentGroup: boolean,
  t: TFunction,
) => {
  if (selectedSpecificAgents) {
    return t('assigned_agents_title');
  }
  if (selectedAgentGroup) {
    return t('agent_groups');
  }
  return t('no_assignment');
};

const AssignmentValues: FC<Props> = ({ showValidations }) => {
  const { t } = useLokaliseTranslation('service_management');
  const { watch } = useFormContext();

  const assignmentValues = watch(Step.ASSIGNMENT);
  const totalAssignedUsers = assignmentValues?.agents?.length || 0;

  const hasError =
    showValidations &&
    !assignmentValues.agents.length &&
    !assignmentValues.agentGroup;
  const selectedSpecificAgents = !!assignmentValues.agents?.length;
  const selectedAgentGroup = !!assignmentValues.agentGroup;

  return (
    <RowItem
      label={getLabel(
        selectedSpecificAgents,
        selectedAgentGroup,
        t as TFunction,
      )}
      value={
        <Typography
          variant="globalS"
          textAlign="right"
        >
          {selectedSpecificAgents
            ? t('agents_count', { count: totalAssignedUsers })
            : assignmentValues.agentGroup?.name}
        </Typography>
      }
      showDivider={false}
      errorMessage={hasError ? t('field_required') : undefined}
    />
  );
};

export default AssignmentValues;
