import { html } from 'lit';
import { query, property } from 'lit/decorators.js';
import { choose } from 'lit/directives/choose.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { boolean } from '../../internal/boolean.mjs';
import { FlowRdfFormControl } from '../../internal/flow-ui-rdf-element.mjs';
import { FormControlController, validValidityState, customErrorValidityState } from '../../internal/form.mjs';
import { isNumber, isNumeric } from '../../internal/type-checks.mjs';
import styles from './color-stop.styles.mjs';

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};
class FlowUiColorStop extends FlowRdfFormControl {
  constructor() {
    super(...arguments);
    // private readonly localize = new LocalizeController(this);
    this.formControlController = new FormControlController(this, {
      assumeInteractionOn: ["flow-ui-blur", "flow-ui-change"]
    });
    this.name = "";
    this.form = "";
    this.required = false;
    this.size = "small";
    this.placeholder = false;
    this.fixed = void 0;
    this.swatches = "";
  }
  connectedCallback() {
    super.connectedCallback();
    this.placeholder = boolean(this.placeholder, true);
    this.required = boolean(this.required, true);
  }
  /** Gets the validity state object. */
  get validity() {
    return this.validate() ? validValidityState : customErrorValidityState;
  }
  /** Gets the validation message. */
  get validationMessage() {
    return this.validate() ? "" : "Invalid regular expression";
  }
  /** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
  checkValidity() {
    return this.validate();
  }
  /** Gets the associated form, if one exists. */
  getForm() {
    return this.formControlController.getForm();
  }
  /** Checks for validity and shows the browser's validation message if the control is invalid. */
  reportValidity() {
    this.input.setCustomValidity(this.validationMessage);
    return this.input.reportValidity();
  }
  /** Sets a custom validation message. Pass an empty string to restore validity. */
  setCustomValidity(message) {
    this.input.setCustomValidity(message);
    this.formControlController.updateValidity();
  }
  handleRemove() {
    this.emit("flow-ui-remove");
  }
  async handleChange(event) {
    const textOptions = this.textOptions?.value ?? [];
    const newValue = {
      value: this.input.value,
      color: this.picker.value,
      options: {
        caseSensitive: textOptions.includes("match-case"),
        regex: textOptions.includes("regex")
      }
    };
    this.value = newValue;
    event.stopPropagation();
    event.preventDefault();
    this.emitChange();
  }
  emitChange() {
    this.emit("flow-ui-change");
  }
  validate() {
    if (this.value.options?.regex) {
      try {
        new RegExp(this.value.value.toString());
      } catch (e) {
        return false;
      }
    }
    return true;
  }
  textInputTemplate() {
    const toolButtons = [];
    if (this.value.options?.caseSensitive) {
      toolButtons.push("match-case");
    }
    if (this.value.options?.regex) {
      toolButtons.push("regex");
    }
    const textOptionsSize = this.size === "small" ? "x-small" : this.size === "medium" ? "small" : "medium";
    return html`
      <flow-ui-input
        part="input"
        class="color-stop__input"
        type="text"
        value=${this.value.value.toString()}
        size=${this.size}
        placeholder="Add a new value"
      >
        <flow-ui-tool-button-group
          class="text-options-button-group"
          slot="suffix"
          size=${textOptionsSize}
          mode="checkbox"
          .value=${toolButtons}
          @flow-ui-change=${this.handleChange}
        >
          <flow-ui-tool-button
            icon-library="system"
            icon="type"
            value="match-case"
            tooltip="Match case"
            tooltip-placement="bottom-end"
          ></flow-ui-tool-button>
          <flow-ui-tool-button
            icon-library="system"
            icon="regex"
            value="regex"
            tooltip="Use regular expression"
            tooltip-placement="bottom-end"
          ></flow-ui-tool-button>
        </flow-ui-tool-button-group>
      </flow-ui-input>
    `;
  }
  numberInputTemplate() {
    const options = this.options;
    return html`
      <flow-ui-input
        type="number"
        part="input"
        class="color-stop__input"
        value=${isNumber(this.value.value) || isNumeric(this.value.value) ? this.value.value : ""}
        min=${ifDefined(options.min)}
        max=${ifDefined(options.max)}
        step=${ifDefined(options.step)}
        placeholder="Add a new number"
        size=${this.size}
      >
        ${options.units && html`
          <span slot="suffix">${options.units}</span>
        `}
      </flow-ui-input>
    `;
  }
  fixedInputTemplate() {
    return html`
      <flow-ui-input
        class="color-stop__input"
        type="text"
        value=${this.fixed ?? "Fixed color"}
        disabled
        size=${this.size}
      ></flow-ui-input>
    `;
  }
  selectInputTemplate() {
    const options = this.options;
    return html`
      <flow-ui-select
        part="select"
        class="color-stop__input"
        size=${this.size}
        value=${this.value.value}
        placeholder="Add a new value"
      >
        ${options.options.map((option) => {
      if (typeof option === "string") {
        return html`
              <flow-ui-option value=${option}>${option}</flow-ui-option>
            `;
      } else {
        return html`
              <flow-ui-option value=${option.value}>${option.name ?? option.value}</flow-ui-option>
            `;
      }
    })}
      </flow-ui-select>
    `;
  }
  render() {
    return html`
      <div
        part="base"
        class=${classMap({
      "color-stop": true,
      "color-stop--small": this.size === "small",
      "color-stop--medium": this.size === "medium",
      "color-stop--large": this.size === "large",
      "color-stop--placeholder": this.placeholder,
      "color-stop--fixed": typeof this.fixed !== "undefined"
    })}
        @flow-ui-change=${this.handleChange}
      >
        <flow-ui-icon-button
          class="color-stop__remove-button"
          label="Remove color stop"
          library="system"
          name="dash-circle"
          confirm="Are you sure?"
          tooltip-placement="right"
          tooltip-distance="1"
          @click=${this.handleRemove}
        ></flow-ui-icon-button>

        ${choose(
      this.fixed ? "fixed" : this.options.type,
      [
        ["fixed", () => this.fixedInputTemplate()],
        ["number", () => this.numberInputTemplate()],
        ["select", () => this.selectInputTemplate()]
      ],
      () => this.textInputTemplate()
    )}

        <flow-ui-color-picker
          part="color-picker"
          size=${this.size}
          format="hex"
          placement="bottom-end"
          skidding="0"
          distance="4"
          opacity
          class="color-stop__picker"
          value=${this.placeholder ? "rgba(0,0,0,0)" : this.value.color}
          .swatches=${this.swatches}
          ?disabled=${this.placeholder}
        ></flow-ui-color-picker>
      </div>
    `;
  }
}
FlowUiColorStop.styles = styles;
__decorateClass([
  query(".color-stop__input")
], FlowUiColorStop.prototype, "input", 2);
__decorateClass([
  query(".color-stop__picker")
], FlowUiColorStop.prototype, "picker", 2);
__decorateClass([
  query(".text-options-button-group")
], FlowUiColorStop.prototype, "textOptions", 2);
__decorateClass([
  property()
], FlowUiColorStop.prototype, "name", 2);
__decorateClass([
  property({ reflect: true })
], FlowUiColorStop.prototype, "form", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], FlowUiColorStop.prototype, "required", 2);
__decorateClass([
  property({ type: Object })
], FlowUiColorStop.prototype, "options", 2);
__decorateClass([
  property({ type: Object })
], FlowUiColorStop.prototype, "value", 2);
__decorateClass([
  property()
], FlowUiColorStop.prototype, "size", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], FlowUiColorStop.prototype, "placeholder", 2);
__decorateClass([
  property({ type: String, reflect: true })
], FlowUiColorStop.prototype, "fixed", 2);
__decorateClass([
  property()
], FlowUiColorStop.prototype, "swatches", 2);

export { FlowUiColorStop as default };
