import { html, type TemplateResult } from 'lit'
import type { IHttpFlow } from '@api-client/core/models/http-flows/HttpFlows.js'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { reactive } from '../../../src/decorators/index.js'
import HttpFlows from '../../../src/elements/http/HttpFlows.element.js'
import '../../../src/define/http/http-flows.js'

const MODEL_STORE_KEY = 'demo.request-ui.editor.flows'

class ComponentDemoPage extends DemoPage {
  override accessor componentName = 'HTTP Flows'

  @reactive() accessor initialized: boolean

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

  constructor() {
    super()
    this.initialized = false
    this.init()
  }

  async init(): Promise<void> {
    await this.restoreModel()
    this.initialized = true
  }

  async restoreModel(): Promise<void> {
    const data = localStorage.getItem(MODEL_STORE_KEY)
    if (!data) {
      return
    }
    try {
      const tmp = JSON.parse(data)
      if (tmp) {
        const model = tmp as IHttpFlow[]
        this.model = model
      }
    } catch {
      //
    }
  }

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

  handleModelChange(e: Event): void {
    const node = e.target as HttpFlows
    const { model = [] } = node
    this.model = model
    this.storeModel()
    console.log('model changed', model)
  }

  contentTemplate(): TemplateResult {
    if (!this.initialized) {
      return this.renderLoader()
    }
    return this.renderDemo()
  }

  renderLoader(): TemplateResult {
    return html`
      <a href="./">Back</a>
      <div class="screen-loader">
        <p>Loading demo page</p>
        <progress></progress>
      </div>
    `
  }

  renderDemo(): TemplateResult {
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <h2 class="title-large">HTTP flows editor</h2>

        <div class="editor-wrapper surface1">
          <http-flows .model="${this.model}" @change="${this.handleModelChange}"></http-flows>
        </div>
      </section>
    `
  }
}

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