import '@operato/i18n/ox-i18n.js'
import '@operato/i18n/ox-i18n-selector.js'
import './change-password'
import './delete-user-popup'
import './my-login-history'

import { css, html, LitElement } from 'lit'
import { customElement, property, query, state } from 'lit/decorators.js'

import { i18next, localize } from '@operato/i18n'
import { notify, openPopup } from '@operato/layout'
import { auth, getLanguages } from '@things-factory/auth-base/dist-client'

@customElement('profile-component')
export class ProfileComponent extends localize(i18next)(LitElement) {
  static styles = [
    css`
      :host {
        display: block;
        background-color: var(--main-section-background-color);
        padding: 15px 0;
      }
      .wrap {
        max-width: var(--profile-wrap-max-width, 400px);
        margin: auto;
        display: grid;
        grid-template-columns: 1fr 1fr;
      }

      * {
        box-sizing: border-box;
      }

      *:focus {
        outline: none;
      }

      input {
        margin: var(--change-password-field-margin);
        border: var(--input-field-border);
        padding: var(--input-padding);
        border-radius: var(--border-radius);
        font: var(--input-font);
        width: var(--change-password-field-width);
      }
      input:focus {
        border: 1px solid var(--focus-background-color);
      }

      .user {
        background: url(/assets/images/icon-profile.png) center top no-repeat;
        margin: var(--profile-icon-margin);
        padding: 180px 20px 20px 20px;
        color: var(--secondary-color);
        font: var(--header-bar-title);
        text-align: center;
      }

      hr {
        width: 100%;
        border: dotted 1px rgba(0, 0, 0, 0.1);
      }

      .wrap * {
        grid-column: span 2;
      }

      label {
        font: bold 14px var(--theme-font);
        color: var(--primary-color);
        text-transform: capitalize;
        grid-column: 1;
      }

      .wrap *.inline {
        grid-column: unset;
      }

      ox-i18n-selector {
        --i18n-selector-field-width: var(--auth-input-field-width);
        --i18n-selector-field-margin: var(--change-password-field-margin);
        --i18n-selector-field-padding: var(--padding-default);
        --i18n-selector-field-border-radius: var(--border-radius);
        margin: var(--change-password-field-margin);
      }

      [danger] {
        --mdc-theme-primary: var(--mdc-danger-button-primary-color);
      }

      footer {
        padding: 20px;
        text-align: center;
      }

      footer p {
        font-size: 14px;
        margin-bottom: 5px;
      }

      footer a {
        color: var(--primary-color);
        text-decoration: none;
        font-weight: bold;
      }
    `
  ]

  @property({ type: String }) email?: string
  @property({ type: String }) name?: string

  @state() languages: { code: string; display: string }[] = []

  @query('#name') nameEl!: HTMLInputElement
  @query('#locale') localeEl!: HTMLInputElement

  async firstUpdated() {
    auth.on('profile', ({ credential }) => {
      this.setCredential(credential)
    })

    this.setCredential(auth.credential)

    this.languages = await getLanguages()
  }

  setCredential(credential) {
    if (credential) {
      this.name = credential.name
      this.email = credential.email
    } else {
      this.name = ''
      this.email = ''
    }
  }

  render() {
    return html`
      <div class="wrap">
        <div class="user">${this.email || ''}</div>

        <label for="name"><ox-i18n slot="title" msgid="label.name"></ox-i18n></label>
        <input id="name" @change=${e => this.onNameChanged(e.target.value)} .value=${this.name || ''} />

        <hr />

        <label for="locale"><ox-i18n slot="title" msgid="label.language"></ox-i18n></label>
        <ox-i18n-selector
          id="locale"
          @change=${e => this.onLocaleChanged(e.detail)}
          value=${i18next.language || 'en-US'}
          .languages=${this.languages}
        ></ox-i18n-selector>

        <hr />

        <label for="change-password">
          <ox-i18n msgid="label.password"></ox-i18n>
        </label>

        <change-password id="change-password"></change-password>

        <footer>
          <p>
            ${i18next.t('text.click login history')}
            <a href="javascript:void(0);" @click=${this.openLoginHistory.bind(this)}
              >${i18next.t('label.login_history')}</a
            >
          </p>
        </footer>
      </div>
    `
  }

  async onNameChanged(name) {
    if (!name) return

    var oldName = this.name

    try {
      const message = await auth.updateProfile({
        name
      })

      notify({
        level: 'info',
        message
      })
    } catch (e: any) {
      this.nameEl.value = oldName || ''

      notify({
        level: 'error',
        message: 'message' in e ? e.message : e
      })
    }
  }

  async onLocaleChanged(value) {
    if (!value) return

    var oldLocale = i18next.language

    try {
      const message = await auth.updateProfile({
        locale: value
      })

      i18next.changeLanguage(value)

      notify({
        level: 'info',
        message
      })
    } catch (e: any) {
      this.localeEl.value = oldLocale

      notify({
        level: 'error',
        message: 'message' in e ? e.message : e
      })
    }
  }

  openLoginHistory() {
    openPopup(html` <my-login-history></my-login-history> `, {
      title: i18next.t('label.login_history')
    })
  }

  deleteUser() {
    openPopup(html` <delete-user-popup></delete-user-popup> `, {
      title: i18next.t('label.delete account')
    })
  }
}
