import { type FC, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import { alpha } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Tooltip from '@material-hu/components/design-system/Tooltip';

import {
  type AutocompleteAnswer,
  type TextStyles,
} from 'src/pages/dashboard/serviceManagement/types';
import { parseAutocompleteAnswer } from 'src/pages/dashboard/serviceManagement/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  TOOLTIP_DELAY_MS,
  TYPOGRAPHY_OVERFLOW_SX_PROPS,
} from '../utils/constants';

type Props = {
  name: string;
  title: string;
  dimensions: {
    width: number;
    height: number;
  };
  answer: AutocompleteAnswer;
  textStyles: TextStyles;
};

const AutocompleteField: FC<Props> = ({
  name,
  title,
  dimensions,
  answer,
  textStyles,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const { setValue, getValues } = useFormContext();

  const value = parseAutocompleteAnswer(answer);

  useEffect(() => {
    const parsed = parseAutocompleteAnswer(answer);
    if (getValues(name) !== parsed) {
      setValue(name, parsed, { shouldDirty: false, shouldValidate: false });
    }
  }, [setValue, getValues, name, answer]);

  return (
    <Tooltip
      title={title}
      delay={TOOLTIP_DELAY_MS}
      description={t('uneditable_field')}
    >
      <Typography
        sx={{
          p: '2px',
          display: 'flex',
          alignItems: 'center',
          width: dimensions.width,
          height: dimensions.height,
          borderRadius: theme => theme.shape.borderRadiusS,
          backgroundColor: ({ palette }) =>
            alpha(palette.new.background.layout.default, 0.5),
          border: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
          opacity: 0.8,
          ...textStyles,
          ...TYPOGRAPHY_OVERFLOW_SX_PROPS,
        }}
      >
        {value}
      </Typography>
    </Tooltip>
  );
};

export default AutocompleteField;
