import { componentName } from '../src/components/mapping-fields/descope-mappings-field';
import { withForm } from './helpers';
import {
  sizeControl,
  fullWidthControl,
  disabledControl,
  directionControl,
  readOnlyControl,
  errorPatternMismatchControl,
  errorMessageIconAttrs,
  errorMessageIconControl,
} from './commonControls';

const Template = ({
  size,
  'full-width': fullWidth,
  disabled,
  direction,
  'label-value': labelValue,
  'label-attr': labelAttr,
  'button-label': buttonLabel,
  separator,
  options,
  readonly,
  'default-values': defaultValues,
  'data-errormessage-pattern-mismatch': customErrorPatternMismatch,
  errorMsgIcon,
}) => {
  let serializedOptions;
  let serializedDefaultValues;

  try {
    serializedOptions = JSON.stringify(options);
    serializedDefaultValues = JSON.stringify(defaultValues);
  } catch (e) {
    // do nothing
  }

  return `
  <descope-mappings-field
    size="${size}"
    disabled="${disabled || false}"
    readonly="${readonly || false}"
    full-width="${fullWidth || false}"
    st-host-direction="${direction ?? ''}"
    options='${serializedOptions || ''}'
    button-label="${buttonLabel}"
    separator="${separator}"
    label-value="${labelValue}"
    label-attr="${labelAttr}"
    data-errormessage-pattern-mismatch="${customErrorPatternMismatch || ''}"
    default-values='${serializedDefaultValues || ''}'
    ${errorMsgIcon ? errorMessageIconAttrs : ''}
  >
  </descope-mappings-field>`;
};

export default {
  component: componentName,
  title: 'descope-mappings-field',
  decorators: [withForm],
  argTypes: {
    'label-value': {
      name: 'Label Value',
      control: { type: 'text' },
    },
    'label-attr': {
      name: 'Label Attribute',
      control: { type: 'text' },
    },
    'button-label': {
      name: 'Button Label',
      control: { type: 'text' },
    },
    separator: {
      name: 'Separator',
      control: { type: 'text' },
    },
    'default-values': {
      name: 'Default Values',
      control: { type: 'object' },
    },
    ...sizeControl,
    ...fullWidthControl,
    ...disabledControl,
    ...readOnlyControl,
    ...directionControl,
    ...errorPatternMismatchControl,
    ...errorMessageIconControl,
  },
};

export const Default = Template.bind({});

Default.args = {
  size: 'md',
  'full-width': false,
  'label-value': 'Value',
  'label-attr': 'Attribute',
  'button-label': 'Add mapping',
  separator: 'map to',
  options: [
    { value: 'itemId1', label: 'item 1' },
    { value: 'itemId2', label: 'item 2' },
    { value: 'itemId3', label: 'item 3' },
    { value: 'itemId4', label: 'item 4' },
  ],
};
