import { Component, h, State, Watch } from '@stencil/core';
import { __ } from '@wordpress/i18n';
import apiFetch from '../../../functions/fetch';
export class ScLogin {
  constructor() {
    this.step = '';
    this.email = '';
    this.password = '';
  }
  /** Focus the password field automatically on password step. */
  handleStepChange() {
    if (this.step === 'password') {
      setTimeout(() => {
        this.passwordInput.triggerFocus();
      }, 50);
    }
  }
  handleEmailChange() {
    this.email = this.emailInput.value;
  }
  /** Get all subscriptions */
  async submitMagicLink() {
    try {
      this.loading = true;
      await apiFetch({
        method: 'POST',
        path: 'surecart/v1/customer_links',
        data: {
          email: this.email,
          return_url: window.location.href,
        },
      });
      this.step = 'complete';
    }
    catch (e) {
      if (e === null || e === void 0 ? void 0 : e.message) {
        this.error = e.message;
      }
      else {
        this.error = __('Something went wrong', 'surecart');
      }
      console.error(this.error);
    }
    finally {
      this.loading = false;
    }
  }
  async login() {
    try {
      this.loading = true;
      const { redirect_url } = await apiFetch({
        method: 'POST',
        path: 'surecart/v1/login',
        data: {
          login: this.email,
          password: this.password,
        },
      });
      if (redirect_url) {
        window.location.replace(redirect_url);
      }
      else {
        window.location.reload();
      }
    }
    catch (e) {
      console.error(this.error);
      this.loading = false;
      if (e === null || e === void 0 ? void 0 : e.message) {
        this.error = e.message;
      }
      else {
        this.error = __('Something went wrong', 'surecart');
      }
    }
  }
  renderInner() {
    if (this.step === 'complete') {
      return (h("sc-alert", { type: "success", open: true },
        h("sc-icon", { slot: "icon", name: "check" }),
        h("span", { slot: "title" }, __('Sent!', 'surecart')),
        h("p", null, __('You should receive an email shortly with a link to login.', 'surecart'))));
    }
    if (this.step === 'password' && this.email) {
      return (h("div", null,
        h("sc-form", { onScFormSubmit: () => this.submitMagicLink() },
          h("sc-button", { type: "primary", submit: true, full: true },
            h("sc-icon", { name: "mail", slot: "prefix" }),
            __('Send a magic link', 'surecart'))),
        h("sc-divider", null, __('or', 'surecart')),
        h("sc-form", { onScFormSubmit: () => this.login() },
          h("sc-input", { label: __('Enter your password', 'surecart'), type: "password", ref: el => (this.passwordInput = el), autofocus: true, required: true, onScChange: e => (this.password = e.target.value) }),
          h("sc-button", { type: "primary", outline: true, submit: true, full: true },
            h("sc-icon", { name: "lock", slot: "prefix" }),
            __('Login', 'surecart')))));
    }
    return (h("sc-form", { onScFormSubmit: () => (this.step = 'password') },
      h("sc-input", { ref: el => (this.emailInput = el), label: "Email Address", onScChange: () => this.handleEmailChange(), required: true, autofocus: true, type: "email" }),
      h("sc-button", { type: "primary", submit: true, full: true },
        h("sc-icon", { name: "arrow-right", slot: "suffix" }),
        __('Next', 'surecart'))));
  }
  renderError() {
    if (this.error) {
      return (h("sc-alert", { open: true, type: "danger" },
        h("span", { slot: "title" }, __('Error', 'surecart')),
        h("span", { innerHTML: this.error })));
    }
  }
  render() {
    return (h("div", { class: "login-form" },
      h("div", { class: "login-form__title", part: "title" },
        h("slot", { name: "title" })),
      h("sc-card", null, this.renderInner()),
      this.loading && h("sc-block-ui", { spinner: true }),
      this.renderError()));
  }
  static get is() { return "sc-login-form"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-login-form.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-login-form.css"]
  }; }
  static get states() { return {
    "step": {},
    "email": {},
    "password": {},
    "loading": {},
    "error": {}
  }; }
  static get watchers() { return [{
      "propName": "step",
      "methodName": "handleStepChange"
    }]; }
}
