import '@material/web/icon/icon.js'

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

import { client } from '@operato/graphql'
import { i18next, localize } from '@operato/i18n'
import { OxPrompt } from '@operato/popup/ox-prompt.js'
import { CommonHeaderStyles } from '@operato/styles'

@customElement('create-domain-popup')
class CreateDomainPopup extends localize(i18next)(LitElement) {
  static styles = [
    CommonHeaderStyles,
    css`
      :host {
        display: flex;
        flex-direction: column;
        background-color: var(--md-sys-color-background);
        overflow: auto;
      }

      form {
        flex: 1;
        padding: var(--spacing-large);
      }

      input.checkValidName {
        background-color: #fce6e6;
      }

      label {
        display: flex;
        flex-direction: column;

        font: var(--label-font);
        color: var(--label-color, var(--md-sys-color-on-surface));
        text-transform: var(--label-text-transform);
      }

      input {
        border: var(--border-dim-color);
        border-radius: var(--border-radius);
        margin: var(--input-margin);
        padding: var(--input-padding);
        background-color: var(--md-sys-color-surface);
        font: var(--input-font);
      }

      [field] {
        grid-column: span 2;
      }
    `
  ]

  @query('input[name="name"]') nameInput!: HTMLInputElement

  render() {
    return html`
      <form>
        <div field grid-span>
          <label
            >${i18next.t('label.x name', { x: i18next.t('label.domain') })}<input
              type="text"
              name="name"
              @input=${this.checkValidation}
              autofocus
          /></label>
        </div>

        <div field grid-span>
          <label>${i18next.t('label.description')}<input type="text" name="description" /></label>
        </div>
      </form>

      <div class="footer">
        <div filler></div>
        <button @click=${e => this.onCreateDomain()} done><md-icon>add</md-icon>${i18next.t('button.create')}</button>
      </div>
    `
  }

  firstUpdated() {
    this.nameInput.focus() // autofocus
  }

  get inputData() {
    return this.renderRoot.querySelectorAll('input')
  }

  checkValidation(e) {
    const currentInput = e.currentTarget
    const regExp = /^[a-zA-Z ]+$/

    if (!regExp.test(currentInput.value)) {
      currentInput.classList.add('checkValidName')
    } else {
      currentInput.classList.remove('checkValidName')
    }
  }

  async onCreateDomain() {
    const domainInput: { [prop: string]: string } = {}
    this.inputData.forEach(data => (domainInput[data.name] = data.value))
    const regExp = /^[a-zA-z0-9- ]+$/

    if (!regExp.test(domainInput.name)) {
      return this.showToast(i18next.t('error: domain name should consist only of letters or dashes'))
    }

    const response = await client.mutate({
      mutation: gql`
        mutation domainRegister($domainInput: DomainGeneratorInput!) {
          domainRegister(domainInput: $domainInput) {
            id
            name
          }
        }
      `,
      variables: { domainInput }
    })

    if (!response.errors) {
      await OxPrompt.open({
        type: 'success',
        title: i18next.t('text.completed'),
        text: i18next.t('text.x_created_successfully', { x: i18next.t('label.domain') }),
        confirmButton: { text: i18next.t('button.confirm') }
      })

      history.back()

      this.dispatchEvent(new CustomEvent('fetch-data'))
    }
  }

  showToast(message) {
    document.dispatchEvent(new CustomEvent('notify', { detail: { message } }))
  }
}
