import {
  createStyleMixin,
  draggableMixin,
  createProxy,
  proxyInputMixin,
  componentNameValidationMixin,
  externalInputMixin,
} from '../../mixins';
import textFieldMappings from '../descope-text-field/textFieldMappings';
import { compose } from '../../helpers';
import { getComponentName } from '../../helpers/componentHelpers';
import {
  inputFloatingLabelStyle,
  resetInputLabelPosition,
  resetInputOverrides,
  useHostExternalPadding,
} from '../../helpers/themeHelpers/resetHelpers';

export const componentName = getComponentName('email-field');

const defaultPattern = "^[\\w\\.\\%\\+\\-']+@[\\w\\.\\-]+\\.[A-Za-z]{2,}$";
const defaultAutocomplete = 'username';

const customMixin = (superclass) =>
  class EmailFieldMixinClass extends superclass {
    init() {
      super.init?.();

      // we need to set the pattern on the base element because vaadin-email-field is overriding it
      this.baseElement.setAttribute('pattern', defaultPattern);

      if (!this.getAttribute('autocomplete')) {
        this.setAttribute('autocomplete', defaultAutocomplete);
      }

      this.createExternalInput();
    }
  };

export const EmailFieldClass = compose(
  createStyleMixin({
    mappings: textFieldMappings,
  }),
  draggableMixin,
  externalInputMixin({
    inputType: 'email',
    inputName: 'email',
    autocompleteType: 'username',
    includeAttrs: ['disabled', 'readonly', 'pattern'],
  }),
  proxyInputMixin({ proxyProps: ['value', 'selectionStart'], useProxyTargets: true }),
  componentNameValidationMixin,
  customMixin
)(
  createProxy({
    slots: ['', 'suffix'],
    wrappedEleName: 'vaadin-email-field',
    style: () => `
			:host {
				display: inline-block;
				max-width: 100%;
				padding: calc(var(${EmailFieldClass.cssVarList.inputOutlineWidth}) + var(${
          EmailFieldClass.cssVarList.inputOutlineOffset
        }));
        box-sizing: border-box;
			}
      ${resetInputLabelPosition('vaadin-email-field')}
			${useHostExternalPadding(EmailFieldClass.cssVarList)}
			${resetInputOverrides('vaadin-email-field', EmailFieldClass.cssVarList)}
      ${inputFloatingLabelStyle()}

      vaadin-email-field[label-type="floating"]:not([focused])[readonly] > input:placeholder-shown {
        opacity: 0;
      }
      vaadin-email-field[label-type="floating"]:not([focused])[disabled] > input:placeholder-shown {
        opacity: 0;
      }

      :host ::slotted(*) {
        -webkit-mask-image: none;
      }

      vaadin-email-field[external-input="true"] > input:not(:placeholder-shown) {
        opacity: 0;
      }
		`,
    excludeAttrsSync: ['tabindex', 'style'],
    componentName,
  })
);
