import { html, TemplateResult } from 'lit'
import { IProperty } from '@api-client/core/models/Property.js'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { reactive } from '../../../src/decorators/index.js'
import '../../../src/define/http/http-headers-form.js'
import HeadersForm from '../../../src/elements/http/HeadersForm.js'

const STORE_KEY = 'demo.request-ui.editor.headers.model'

class ComponentDemoPage extends DemoPage {
  override accessor componentName = 'Headers Editing'

  @reactive() accessor model: IProperty[] = []

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

  restoreModel(): void {
    const data = localStorage.getItem(STORE_KEY)
    if (!data) {
      return
    }
    try {
      const tmp = JSON.parse(data)
      if (Array.isArray(tmp)) {
        this.model = tmp as IProperty[]
      }
    } catch {
      //
    }
  }

  storeModel(): void {
    const { model } = this
    localStorage.setItem(STORE_KEY, JSON.stringify(model))
  }

  handleChange(e: Event): void {
    const input = e.target as HeadersForm
    console.log('Change from the editor', input.model)
    this.model = input.model
    this.storeModel()
  }

  contentTemplate(): TemplateResult {
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <h2 class="title-large">HTTP headers form</h2>
        <http-headers-form .model="${this.model}" @change="${this.handleChange}"></http-headers-form>
      </section>
    `
  }
}

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