import { Component, h, State } from '@stencil/core';
import { isNone, isSome, none, toUndefined } from 'fp-ts/lib/Option';
import { Subscription } from 'rxjs';
import editBenefitQuery from '../edit-benefit.query';
import editBenefitService from '../edit-benefit.service';
var InputState;
(function (InputState) {
  InputState[InputState["Pristine"] = 0] = "Pristine";
  InputState[InputState["Validated"] = 1] = "Validated";
})(InputState || (InputState = {}));
var UiState;
(function (UiState) {
  UiState[UiState["Collapsed"] = 0] = "Collapsed";
  UiState[UiState["Editing"] = 1] = "Editing";
})(UiState || (UiState = {}));
export class BenefitUrl {
  constructor() {
    this.benefitUrl = none;
    this.uiState = UiState.Collapsed;
    this.inputState = InputState.Pristine;
    this.storeSubscription = new Subscription();
    this.absoluteUrlRegex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/;
    this.relativeUrlRegex = /^\/\S+/;
    this.httpSchemeRegex = /^https?:\/\//i;
  }
  componentWillLoad() {
    this.storeSubscription.add(editBenefitQuery.draftBenefitUrl$.subscribe((url) => {
      this.benefitUrl = url;
    }));
  }
  disconnectedCallback() {
    this.storeSubscription.unsubscribe();
  }
  render() {
    return this.uiState === UiState.Editing ? this.renderInProgress() : this.renderEmptyState();
  }
  renderEmptyState() {
    return (h("div", { class: "row mb-2" },
      h("div", { class: "col-12 d-flex" },
        h("button", { type: "button", class: "uiid-benefit-urllink btn btn-light border flex-fill d-flex align-items-center rounded p-0 w-100", onClick: (_) => {
            this.uiState = UiState.Editing;
          } },
          isSome(this.benefitUrl) ? (h("ap-ben-icon", { class: "weblink-icon m-4", iconPrefix: "fas", iconId: "globe" })) : (h("ap-ben-icon", { class: "text-muted m-4", iconPrefix: "fal", iconId: "link" })),
          h("div", { class: "d-flex flex-column text-left overflow-hidden" },
            h("span", null, isSome(this.benefitUrl) ? 'Weblink' : 'Add weblink'),
            h("small", { class: "text-muted text-truncate w-100" }, isSome(this.benefitUrl)
              ? toUndefined(this.benefitUrl)
              : 'Add a web URL to supporting material')),
          h("button", { class: "btn ml-auto px-3", type: "button", hidden: isNone(this.benefitUrl), onClick: (event) => this.clear(event) },
            h("ap-ben-icon", { iconPrefix: "fal", iconId: "trash" }))))));
  }
  renderInProgress() {
    return (h("div", { class: "row mb-2 no-gutters border rounded" },
      h("div", { class: "blur-backdrop", onClick: (_) => {
          this.uiState = UiState.Collapsed;
        } }),
      h("div", { class: `col-12 p-3 ${this.inputState === InputState.Validated ? 'was-validated' : ''}` },
        h("div", { class: "row" },
          h("div", { class: "col-12 d-flex" },
            h("div", { class: "d-flex flex-column flex-fill" },
              h("input", { type: "text", class: "uiid-enter-benefit-urllink form-control d-inline", name: "benefitUrl", value: toUndefined(this.benefitUrl), required: true, onInput: (_) => this.onBenefitUrlInput(), ref: (element) => (this.inputElement = element), placeholder: "https://www.example.com" }),
              h("div", { class: "invalid-feedback" }, "Please provide a valid URL for your benefit.")),
            h("button", { type: "button", class: "uiid-verify-benefit-urllink btn btn-primary ml-2 d-inline align-self-start", onClick: (_) => {
                this.submit();
              } },
              h("ap-ben-icon", { iconPrefix: "fal", iconId: "check" })))))));
  }
  getUrlRegex(url) {
    if (this.relativeUrlRegex.test(url)) {
      return this.relativeUrlRegex;
    }
    return this.absoluteUrlRegex;
  }
  formatUrl(unformattedUrl) {
    if (unformattedUrl === '') {
      return '';
    }
    if (unformattedUrl[0] === '/') {
      return unformattedUrl;
    }
    if (this.httpSchemeRegex.test(unformattedUrl)) {
      return unformattedUrl;
    }
    try {
      return new URL(`https://${unformattedUrl}`).href;
    }
    catch (_a) {
      return unformattedUrl;
    }
  }
  onBenefitUrlInput() {
    const currentValue = this.inputElement.value.trim();
    this.inputElement.pattern = this.getUrlRegex(currentValue).source;
  }
  submit() {
    const benefitUrl = this.inputElement.value.trim();
    const formattedUrl = this.formatUrl(benefitUrl);
    this.inputElement.value = formattedUrl;
    this.inputElement.pattern = this.getUrlRegex(formattedUrl).source;
    this.inputState = InputState.Validated;
    if (this.inputElement.checkValidity() && formattedUrl !== '') {
      this.uiState = UiState.Collapsed;
      editBenefitService.updateDraftUrl(formattedUrl);
    }
    else {
      this.inputElement.focus();
    }
  }
  clear(event) {
    event.stopPropagation();
    this.inputState = InputState.Pristine;
    editBenefitService.clearDraftUrl();
  }
  static get is() { return "ap-ben-benefit-url"; }
  static get originalStyleUrls() { return {
    "$": ["benefit-url.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["benefit-url.css"]
  }; }
  static get states() { return {
    "benefitUrl": {},
    "uiState": {},
    "inputState": {}
  }; }
}
