import '@material/web/checkbox/checkbox.js'
import '@operato/i18n/ox-i18n.js'
import '@things-factory/setting-base'

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

import { i18next, localize } from '@operato/i18n'
import { clientSettingStore } from '@operato/shell/object-store.js'

@customElement('board-view-setting-let')
export class BoardViewSettingLet extends localize(i18next)(LitElement) {
  static styles = [
    css`
      label {
        display: flex;
        gap: 10px;
        align-items: center;

        font: var(--label-font);
        color: var(--md-sys-color-on-surface);
        text-transform: var(--label-text-transform);
      }
    `
  ]

  @property({ type: Boolean }) autoRefresh?: boolean

  render() {
    return html`
      <setting-let>
        <ox-i18n slot="title" msgid="title.board view setting"></ox-i18n>

        <div slot="content">
          <label>
            <md-checkbox id="auto-refresh" @change=${e => this.onChange(e)} ?checked=${this.autoRefresh}></md-checkbox>
            ${String(i18next.t('label.auto refresh board view'))}
          </label>
        </div>
      </setting-let>
    `
  }

  async firstUpdated() {
    const { autoRefresh = true } = (await clientSettingStore.get('board-view'))?.value || {}
    this.autoRefresh = autoRefresh
  }

  async onChange(e) {
    this.autoRefresh = e.target.checked

    const { autoRefresh: valueFromStore } = (await clientSettingStore.get('board-view'))?.value || {}
    if (this.autoRefresh === valueFromStore) {
      return
    }

    try {
      await clientSettingStore.put({
        key: 'board-view',
        value: {
          autoRefresh: this.autoRefresh
        }
      })
    } catch (e) {
      console.error(e)
    }
  }
}
