import { useController } from 'react-hook-form';

import { type Theme } from '@material-hu/mui/index';

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

import TypographyLinkSensitive from '../../../general/TypographyLinkSensitive';

type Props = {
  name: string;
  title: string;
  required: boolean;
  type: InputType;
};

const noOptionalLabelTypes = [InputType.INFO, InputType.AUTOCOMPLETE];

const ComponentTitle = ({ name, title, required, type }: Props) => {
  const { t } = useLokaliseTranslation('service_management');
  const { fieldState } = useController({
    name,
  });

  const getTextColor = (theme: Theme) => {
    if (type === InputType.AUTOCOMPLETE) {
      return theme.palette.new.text.neutral.disabled;
    }
    const hasError = !!Object.values(fieldState.error ?? {}).length;
    return hasError
      ? theme.palette.new.text.feedback.error
      : theme.palette.new.text.neutral.default;
  };

  const getSuffix = () => {
    if (noOptionalLabelTypes.includes(type)) return '';
    if (required) return ' *';
    return ` (${t('optional')})`;
  };

  return (
    <TypographyLinkSensitive
      variant="globalS"
      fontWeight="fontWeightSemiBold"
      sx={{
        color: theme => getTextColor(theme),
      }}
    >
      {title}
      {getSuffix()}
    </TypographyLinkSensitive>
  );
};

export default ComponentTitle;
