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

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

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

import {
  ConditionType,
  getJoinOperators,
  JoinOperatorType,
} from 'src/components/Condition/components/constants';

import MenuSelect from '../MenuSelect';

const JoinSelector = ({
  index,
  name,
  onlyAnd,
}: {
  index: number;
  name: string;
  onlyAnd?: boolean;
}) => {
  const { t } = useLokaliseTranslation(['backoffice_only']);
  const { getValues, setValue, watch } = useFormContext();

  /** Propagates first join operator to all conditions */
  const propagateJoinOperator = (value?: JoinOperatorType[]) => {
    getValues(name).forEach((_: ConditionType, fieldIndex: number) => {
      setValue(`${name}[${fieldIndex}].joinOperator`, value?.[0]?.id);
    });
  };

  if (index === 0) {
    return (
      <Typography
        variant="globalXS"
        fontWeight="semiBold"
        color={theme => theme.palette.new.text.neutral.brand}
        sx={{
          width: '70px',
          textAlign: 'center',
        }}
      >
        {t('general:when')}
      </Typography>
    );
  }

  if (index === 1) {
    return onlyAnd ? (
      <Typography
        variant="globalXS"
        fontWeight="semiBold"
        color={theme => theme.palette.new.text.neutral.brand}
        sx={{
          width: '55px',
          textAlign: 'center',
        }}
      >
        {t(
          `backoffice_only:condition.${watch(`${name}[${index}].joinOperator`)}`,
        )}
      </Typography>
    ) : (
      <MenuSelect
        items={getJoinOperators(t)}
        name={`${name}[${index}].joinOperator`}
        isDisabled={onlyAnd}
        position="left"
        singleObject
        buttonMaxWidth="70px"
        minWidth="70px"
        onChange={propagateJoinOperator}
      />
    );
  }

  return (
    <Typography
      variant="globalXS"
      fontWeight="semiBold"
      color={theme => theme.palette.textColors?.primaryText}
      sx={{
        width: '70px',
        textAlign: 'center',
      }}
    >
      {t(
        `backoffice_only:condition.${watch(`${name}[${index}].joinOperator`)}`,
      )}
    </Typography>
  );
};

export default JoinSelector;
