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

import { i18next } from '@operato/i18n'

@customElement('create-user')
class CreateUser extends LitElement {
  static styles = css`
    :host {
      --mdc-text-field-fill-color: var(--theme-white-color);
      background-color: var(--theme-white-color);
      margin: var(--margin-wide) 0;
      padding: var(--padding-wide);
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);

      display: grid;
      grid-template-columns: 1fr 2fr auto;
      gap: 5px 15px;
      clear: both;
      max-width: var(--input-container-max-width);

      align-items: center;
    }

    mwc-button {
      margin: var(--input-margin);
    }

    @media screen and (max-width: 480px) {
      :host {
        grid-template-columns: 1fr 1fr;
      }

      mwc-button {
        grid-column: span 2;

        margin: var(--input-margin);
      }
    }
  `

  @query('[name=name]') nameInput!: HTMLInputElement
  @query('[name=email]') emailInput!: HTMLInputElement

  render() {
    return html`
      <mwc-textfield
        type="text"
        name="name"
        label=${String(i18next.t('label.x name', { x: i18next.t('label.user') }))}
      ></mwc-textfield>

      <mwc-textfield type="email" name="email" label=${String(i18next.t('field.email'))}></mwc-textfield>

      <mwc-button
        @click=${this.onCreateUser.bind(this)}
        outlined
        label=${String(i18next.t('button.create'))}
      ></mwc-button>
    `
  }

  async onCreateUser() {
    try {
      if (!this.emailInput.checkValidity()) {
        throw new Error(i18next.t('error.not valid pattern of type', { type: 'e-mail' }))
      }

      if (!this.nameInput.value) {
        throw new Error(i18next.t('error.value is empty', { value: 'name' }))
      }

      const user = {
        name: this.nameInput.value.trim(),
        email: this.emailInput.value.trim()
      }

      await this.dispatchEvent(new CustomEvent('create-user', { detail: user }))

      this.nameInput.value = ''
      this.emailInput.value = ''
    } catch (e: any) {
      document.dispatchEvent(
        new CustomEvent('notify', {
          detail: {
            level: 'error',
            message: 'message' in e ? e.message : e
          }
        })
      )
    }
  }
}
