import '@material/mwc-icon'
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'

import { RoleSelector } from './role-selector'

@customElement('partner-role-editor')
class PartnerRoleEditor extends localize(i18next)(LitElement) {
  static styles = [
    css`
      :host {
        display: flex;
        flex-direction: column;

        border: 1px solid var(--primary-color);
        padding: var(--padding-default);
        font: normal 15px var(--theme-font);
        color: var(--secondary-color);
      }
      [buttons] {
        margin: 0;
        padding: var(--padding-default);
        background-color: rgba(var(--primary-color-rgb), 0.2);
      }
      mwc-button {
        margin-right: var(--padding-narrow);
      }
      [danger] {
        --mdc-theme-primary: var(--mdc-danger-button-primary-color);
      }
    `
  ]

  @property({ type: Object }) customer: any
  @property({ type: Array }) roles: any[] = []
  @property({ type: Array }) grantingRoles: any[] = []

  @query('role-selector') roleSelector!: RoleSelector

  render() {
    const roles = this.roles || []
    const grantingRoles = this.grantingRoles || []

    return html`
      <role-selector .roles="${roles}" .userRoles="${grantingRoles}"></role-selector>

      <div buttons>
        <mwc-button @click=${this.onSave} raised label="${i18next.t('button.save')}"></mwc-button>
        <mwc-button
          @click=${this.onTerminateContract}
          raised
          danger
          label="${i18next.t('button.terminate contract')}"
        ></mwc-button>
      </div>
    `
  }

  updated(changes) {
    if (changes.has('customer')) {
      this.refreshRoles()
    }
  }

  async refreshRoles() {
    const response = await client.query({
      query: gql`
        query roles($customerId: String!) {
          roles {
            items {
              id
              name
              description
            }
            total
          }
          grantingRoles(customerId: $customerId) {
            id
            role {
              id
              name
              description
            }
          }
        }
      `,
      variables: { customerId: this.customer.id },
      context: gqlContext()
    })

    if (!response.errors?.length) {
      this.roles = response.data.roles.items
      this.grantingRoles = response.data.grantingRoles.map(grantingRole => grantingRole.role)
    } else {
      this.roles = []
      this.grantingRoles = []
    }
  }

  async onSave() {
    const roles = this.roleSelector.selectedRoles()

    const response = await client.mutate({
      mutation: gql`
        mutation grantRoles($customerId: String!, $roles: [RolePatch!]!) {
          grantRoles(customerId: $customerId, roles: $roles)
        }
      `,
      variables: { customerId: this.customer.id, roles },
      context: gqlContext()
    })

    if (!response.errors?.length) {
      this.showToast(i18next.t('text.data_updated_successfully'))
    }
  }

  async onTerminateContract() {
    if (
      await OxPrompt.open({
        title: i18next.t('text.are_you_sure'),
        text: i18next.t('text.are_you_sure_to_terminate_contract'),
        confirmButton: { text: i18next.t('button.terminate contract') },
        cancelButton: { text: i18next.t('button.cancel') }
      })
    ) {
      const response = await client.mutate({
        mutation: gql`
          mutation terminateContract($partnerName: String!) {
            terminateContract(partnerName: $partnerName)
          }
        `,
        variables: { partnerName: this.customer.name },
        context: gqlContext()
      })

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

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

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