import '@operato/i18n/ox-i18n.js'

import { html } from 'lit'
import { customElement, query } from 'lit/decorators.js'

import { i18next } from '@operato/i18n'

import { AbstractSign } from '../../components/abstract-sign'
import { generatePasswordPatternHelp, generatePasswordPatternRegExp } from '../../utils/password-rule'

@customElement('auth-signup')
export class AuthSignup extends AbstractSign {
  private passwordPattern?: string
  private passwordHelp?: string

  get pageName() {
    return 'sign up'
  }

  get actionUrl() {
    return '/auth/signup'
  }

  @query('#confirm-password') confirmPass!: HTMLInputElement

  get formfields() {
    const { name = '', email = '' } = this.data || {}

    return html`
      <div class="field">
        <mwc-textfield
          name="name"
          type="text"
          label=${String(i18next.t('field.name'))}
          .value=${name}
          required
        ></mwc-textfield>
      </div>
      <div class="field">
        <mwc-textfield
          name="email"
          type="email"
          label=${String(i18next.t('field.email'))}
          required
          .value=${email}
          .validationMessage=${String(i18next.t('text.invalid-email'))}
        ></mwc-textfield>
      </div>
      <div class="field">
        <mwc-textfield
          name="password"
          type="password"
          label=${String(i18next.t('field.password'))}
          .pattern=${this.passwordPattern || ''}
          helper=${this.passwordHelp || ''}
          helperPersistent
          required
          @input=${e => {
            var val = e.target.value
            this.confirmPass.setAttribute('pattern', val.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '[$&]'))
          }}
          .validationMessage=${this.passwordHelp || ''}
        ></mwc-textfield>
      </div>
      <div class="field">
        <mwc-textfield
          id="confirm-password"
          name="confirm-password"
          type="password"
          label=${String(i18next.t('field.confirm password'))}
          required
          .validationMessage=${String(i18next.t('text.passwords do not match'))}
        ></mwc-textfield>
      </div>
      <mwc-button class="ui button" raised @click=${e => this._onSubmit(e)}>
        <ox-i18n msgid="field.${this.pageName}"></ox-i18n>
      </mwc-button>
    `
  }

  languageUpdated() {
    this.passwordPattern = generatePasswordPatternRegExp(this.data.passwordRule).source
    this.passwordHelp = generatePasswordPatternHelp(this.data.passwordRule)
  }

  get links() {
    return html`
      <a class="link" href="/auth/signin">
        <mwc-button><ox-i18n msgid="field.sign in"></ox-i18n></mwc-button>
      </a>
    `
  }
}
