import '@things-factory/component-ui'
import '../../components/create-role'
import '../../components/role-edit-form'
import '../../components/role-privilege-editor'

import gql from 'graphql-tag'
import { css, html } from 'lit'
import { customElement, property, query } from 'lit/decorators.js'
import { connect } from 'pwa-helpers/connect-mixin.js'

import { client, gqlContext } from '@operato/graphql'
import { i18next } from '@operato/i18n'
import { InheritedValueType, PageView, store } from '@operato/shell'

@customElement('role-management')
class RoleManagement extends connect(store)(PageView) {
  static styles = [
    css`
      :host {
        display: flex;
        flex-direction: column;
        background-color: var(--main-section-background-color);
        padding: var(--padding-wide);
        overflow: auto;
      }

      [subtitle] {
        padding: var(--subtitle-padding);
        font: var(--subtitle-font);
        color: var(--subtitle-text-color);
      }

      input {
        display: block;
      }

      #roles-privileges {
        flex: 1;
        display: flex;
        margin-top: var(--margin-default);
        max-width: var(--content-container-max-width);
        flex-direction: row;
        overflow: auto;
        border-top: var(--border-dark-color);
      }
    `
  ]

  @property({ type: String }) title: string = ''
  @property({ type: Object }) role: any
  @property({ type: Array }) roles: any[] = []
  @property({ type: Object }) updateRoleObj: any

  get context() {
    return {
      title: i18next.t('text.role_management'),
      help: 'auth/roles'
    }
  }

  render() {
    const data = {
      roles: this.roles || []
    }

    return html`
      <create-role
        @fetch-roles=${async () => {
          this.roles = await this.fetchRoles()
        }}
      ></create-role>

      <div subtitle>${i18next.t('text.registered roles')}</div>
      <div id="roles-privileges">
        <quick-find-list
          .data="${data}"
          .openHeaderRenderer=${role =>
            html`
              <role-edit-form .role="${role}" @roleChanged="${e => (this.updateRoleObj = e.detail)}"></role-edit-form>
            `}
          .contentRenderer="${(role, _currentTabKey) => html`
            <role-privilege-editor
              .updateRoleObj=${this.updateRoleObj || {}}
              .role=${role}
              @fetch-roles=${async () => {
                this.roles = await this.fetchRoles()
                await this.updateComplete
                this.quickFindList.openByKey(role.id)
              }}
            ></role-privilege-editor>
          `}"
        ></quick-find-list>
      </div>
    `
  }

  @query('quick-find-list') quickFindList!: HTMLElement & { openByKey: (roleId: string) => void }

  async pageUpdated(changes, lifecycle, before) {
    if (this.active) {
      this.roles = await this.fetchRoles()
      this.role = this.roles && this.roles[0]
    }
  }

  async fetchRoles() {
    const response = await client.query({
      query: gql`
        query roles($sortings: [Sorting!], $inherited: InheritedValueType) {
          roles(sortings: $sortings, inherited: $inherited) {
            items {
              id
              name
              description
              privileges {
                id
                name
              }
            }
            total
          }
        }
      `,
      variables: {
        sortings: [{ name: 'name' }],
        inherited: InheritedValueType.Include
      },
      context: gqlContext()
    })

    return response.data.roles.items
  }
}
