import './user-role-editor'

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

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

@customElement('invite-user')
class InviteUser extends localize(i18next)(LitElement) {
  static styles = css`
    :host {
      display: grid;
    }

    input {
      flex: 1;

      border: var(--border-dim-color);
      border-radius: var(--border-radius);
      margin: var(--input-margin);
      padding: var(--input-padding);
      min-width: 250px;
      font: var(--input-font);
    }

    md-outlined-button {
      margin: var(--input-margin);
      text-transform: capitalize;
    }
  `

  @query('input[name=username]') userIdInput!: HTMLInputElement

  render() {
    return html`
      <input
        name="username"
        type="text"
        required
        name="username"
        autocapitalize="off"
        placeholder=${String(i18next.t('text.user invitation prompt'))}
        pattern="^(?:[A-Za-z0-9]*|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,})$"
      />
      <md-outlined-button @click=${this.invite.bind(this)}>
        <md-icon slot="icon">group_add</md-icon>${String(i18next.t('label.invite user'))}
      </md-outlined-button>
    `
  }

  async invite() {
    try {
      if (!this.userIdInput.checkValidity()) {
        throw new Error(i18next.t('error.not valid pattern of type', { type: 'user-id or email' }))
      }

      if (
        await OxPrompt.open({
          title: i18next.t('text.are_you_sure'),
          text: i18next.t('text.do_you_want_to_invite_x', { x: i18next.t(`label.user`) }),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })
      ) {
        await this.inviteUser(this.userIdInput.value)

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

  async inviteUser(username) {
    const response = await client.mutate({
      mutation: gql`
        mutation inviteUser($username: String!) {
          inviteUser(username: $username)
        }
      `,
      variables: { username },
      context: gqlContext()
    })

    if (!response.errors) {
      await OxPrompt.open({
        title: i18next.t('text.completed'),
        confirmButton: { text: i18next.t('button.confirm') }
      })

      this.userIdInput.value = ''
    }
  }
}
