import '@things-factory/auth-ui'

import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit'
import { customElement, property, 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-customer')
class InviteCustomer extends localize(i18next)(LitElement) {
  static styles = [
    css`
      input {
        border: var(--border-dark-color);
        border-radius: var(--border-radius);
        margin: var(--input-margin);
        padding: var(--input-padding);
        min-width: 250px;
        font: var(--input-font);
      }
      mwc-button {
        margin: var(--input-margin);
      }
      @media screen and (max-width: 480px) {
        div {
          display: grid;
        }
      }
    `
  ]

  @property({ type: Array }) customers: any[] = []

  @query('input#customer-name') customerNameInput!: HTMLInputElement

  render() {
    return html`
      <div>
        <input id="customer-name" required />
        <mwc-button
          @click=${this.invite.bind(this)}
          outlined
          icon="group_add"
          label=${String(i18next.t('label.invite customer'))}
        ></mwc-button>
      </div>
    `
  }

  async invite() {
    try {
      if (!this.customerNameInput.value)
        throw new Error(i18next.t('error.value is empty', { value: i18next.t('field.name') }))

      if (this.customers.find(c => c.name?.toLowerCase() === this.customerNameInput.value.toLowerCase())) {
        throw new Error(
          i18next.t('error.x already exists in y', { x: this.customerNameInput.value, y: i18next.t('field.customer') })
        )
      }

      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.partner`) }),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })
      ) {
        const customerDomainName = this.customerNameInput.value

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

        if (!response.errors) {
          const answer = this.dispatchEvent(new CustomEvent('invitationCompleted'))

          if (answer) {
            await OxPrompt.open({
              type: 'success',
              title: i18next.t('text.completed'),
              confirmButton: { text: i18next.t('button.confirm') }
            })
          }

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