import { html, TemplateResult } from 'lit'
import { IProperty, Property } from '@api-client/core/models/Property.js'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { reactive } from '../../../src/decorators/index.js'
import env from '../../env.js'
import VariablesEditor from '../../../src/elements/environment/VariablesEditor.js'

import '../../../src/define/environment/variables-editor.js'
import '../../../src/md/button/ui-button.js'

const storeKey = 'api-client.demo.elements.environment.variables-editor'

class ComponentDemoPage extends DemoPage {
  override accessor componentName = 'Variables editor'

  @reactive() accessor variables: IProperty[] | undefined

  constructor() {
    super()
    this.restoreValues()
  }

  fromEnvironment(): void {
    const result: IProperty[] = []
    const vars = env.systemVariables as Record<string, string>
    Object.keys(vars).forEach((key) => {
      const value = vars[key]
      const prop = Property.String(key, String(value))
      result.push(prop.toJSON())
    })
    this.variables = result
  }

  restoreValues(): void {
    const data = localStorage.getItem(storeKey)
    if (!data) {
      this.fromEnvironment()
      return
    }
    try {
      const list = JSON.parse(data) as IProperty[]
      if (Array.isArray(list)) {
        this.variables = list
      } else {
        this.fromEnvironment()
      }
    } catch {
      this.fromEnvironment()
    }
  }

  storeValues(): void {
    const { variables } = this
    if (!variables) {
      localStorage.removeItem(storeKey)
    } else {
      localStorage.setItem(storeKey, JSON.stringify(variables))
    }
  }

  loadSystem(): void {
    this.fromEnvironment()
    this.storeValues()
  }

  _changedHandler(): void {
    console.log('change')
    const editor = document.querySelector('variables-editor') as VariablesEditor
    this.variables = editor.variables
    this.storeValues()
  }

  contentTemplate(): TemplateResult {
    return html`
      <a href="./">Back</a>
      ${this.renderDataControl()}
      <section class="demo-section">
        <variables-editor .variables="${this.variables}" @change="${this._changedHandler}"></variables-editor>
      </section>
    `
  }

  renderDataControl(): TemplateResult {
    return html`
      <section class="demo-section">
        <h2 class="title-large">Data control</h2>
        <ui-button color="outlined" @click="${this.loadSystem}">Load system variables</ui-button>
      </section>
    `
  }
}

const instance = new ComponentDemoPage()
instance.render()
