import { Component, Prop, h, Watch, State, Host, Listen, Event } from '@stencil/core';
import { __ } from '@wordpress/i18n';
import apiFetch from '../../../functions/fetch';
export class ScLoginProvider {
  /** Listen for open event. */
  handleLoginPrompt() {
    this.open = true;
  }
  /** Focus on first input. */
  handleLoginDialogChange(val) {
    if (val) {
      setTimeout(() => {
        this.loginForm.querySelector('sc-input').triggerFocus();
      }, 100);
    }
  }
  handleLoggedInChange(val, prev) {
    if (prev === false && val) {
      this.notice = true;
    }
  }
  handleOrderChange(val, prev) {
    if ((val === null || val === void 0 ? void 0 : val.updated_at) !== (prev === null || prev === void 0 ? void 0 : prev.updated_at)) {
      this.notice = false;
    }
  }
  /** Handle form submit. */
  async handleFormSubmit(e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    this.error = null;
    const { login, password } = await e.target.getFormJson();
    try {
      this.loading = true;
      const { name, email } = (await apiFetch({
        method: 'POST',
        path: 'surecart/v1/login',
        data: {
          login,
          password,
        },
      }));
      this.scSetLoggedIn.emit(true);
      this.scSetCustomer.emit({ name, email });
      this.open = false;
    }
    catch (e) {
      console.error(e);
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.loading = false;
    }
  }
  render() {
    return (h(Host, null,
      !!this.notice && (h("sc-alert", { type: "success", open: true, style: { marginBottom: 'var(--sc-form-row-spacing)' }, closable: true },
        h("span", { slot: "title" }, __('Welcome back!', 'surecart')),
        __('You have logged in successfully.', 'surecart'))),
      h("slot", null),
      !this.loggedIn && (h("sc-dialog", { label: __('Login to your account', 'surecart'), open: this.open, onScRequestClose: () => (this.open = false) },
        h("sc-form", { ref: el => (this.loginForm = el), onScFormSubmit: e => {
            e.preventDefault();
            e.stopImmediatePropagation();
          }, onScSubmit: e => this.handleFormSubmit(e) },
          !!this.error && (h("sc-alert", { type: "danger", open: !!this.error }, this.error)),
          h("sc-input", { label: __('Email or Username', 'surecart'), type: "text", name: "login", required: true, autofocus: this.open }),
          h("sc-input", { label: __('Password', 'surecart'), type: "password", name: "password", required: true }),
          h("sc-button", { type: "primary", full: true, loading: this.loading, submit: true }, __('Login', 'surecart')))))));
  }
  static get is() { return "sc-login-provider"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-login-provider.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-login-provider.css"]
  }; }
  static get properties() { return {
    "loggedIn": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is the user logged in."
      },
      "attribute": "logged-in",
      "reflect": false
    },
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "notice": {},
    "open": {},
    "loading": {},
    "error": {}
  }; }
  static get events() { return [{
      "method": "scSetLoggedIn",
      "name": "scSetLoggedIn",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      }
    }, {
      "method": "scSetCustomer",
      "name": "scSetCustomer",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "{ email: string; name?: string }",
        "resolved": "{ email: string; name?: string; }",
        "references": {}
      }
    }]; }
  static get watchers() { return [{
      "propName": "open",
      "methodName": "handleLoginDialogChange"
    }, {
      "propName": "loggedIn",
      "methodName": "handleLoggedInChange"
    }, {
      "propName": "order",
      "methodName": "handleOrderChange"
    }]; }
  static get listeners() { return [{
      "name": "scLoginPrompt",
      "method": "handleLoginPrompt",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
