import {
  IconField,
  BooleanField,
  Visibility,
} from '@hubspot/cms-components/fields';
import { ContentFieldsProps } from './types.js';

const ContentFields = ({
  iconLabel = 'Icon',
  iconName = 'icon',
  iconDefault = { name: 'angle-right', unicode: 'f105', type: 'SOLID' },
  addIconToggle = false,
  ...rest
}: ContentFieldsProps) => {
  let showIconLabel = 'Show icon';
  let showIconName = 'showIcon';
  let showIconDefault = false;

  if (addIconToggle && 'showIconDefault' in rest) {
    showIconLabel = rest.showIconLabel ?? showIconLabel;
    showIconName = rest.showIconName ?? showIconName;
    // This single check tells TS that we are in the `IconContentFieldsWithToggleProps` type.
    showIconDefault = rest.showIconDefault ?? showIconDefault;
  }

  const SHOW_ICON_VISIBILITY_RULES: Visibility = {
    operator: 'EQUAL',
    controlling_field: 'iconComponentShowIcon',
    controlling_value_regex: 'true',
  };

  return (
    <>
      {addIconToggle && (
        <BooleanField
          label={showIconLabel}
          name={showIconName}
          id="iconComponentShowIcon"
          display="toggle"
          default={showIconDefault}
        />
      )}
      <IconField
        label={iconLabel}
        name={iconName}
        visibility={addIconToggle ? SHOW_ICON_VISIBILITY_RULES : undefined}
        default={iconDefault}
      />
    </>
  );
};

export default ContentFields;
