import { useMemo } from 'react';

import { SectionComponent } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { TOOLTIP_DELAY_MS } from '../utils/constants';
import { getFieldError } from '../utils/utils';

type Props = {
  showErrors: boolean;
  field: SectionComponent;
  answer: any;
};

const useFieldErrorMessages = ({ showErrors, field, answer }: Props) => {
  const { t } = useLokaliseTranslation('service_management');
  const {
    content: { title, required },
  } = field;

  const errorMessages: string[] | null = useMemo(() => {
    if (showErrors) {
      return getFieldError(field, answer, t) || null;
    }
    return null;
  }, [showErrors, answer, t, field]);

  const getTooltipProps = () => {
    const fieldTitle = `${title}${required ? ' *' : ''}`;
    if (hasErrors) {
      return {
        title: fieldTitle,
        description: (
          <span style={{ whiteSpace: 'pre-line' }}>
            {errorMessages?.join('\n')}
          </span>
        ),
        delay: TOOLTIP_DELAY_MS,
      };
    }
    return {
      description: <span style={{ whiteSpace: 'pre-line' }}>{fieldTitle}</span>,
      delay: TOOLTIP_DELAY_MS,
    };
  };

  const hasErrors = showErrors && !!errorMessages && errorMessages?.length > 0;

  return {
    getTooltipProps,
    hasErrors,
    errorMessages,
  };
};

export default useFieldErrorMessages;
