import { TemplateResult, html, PropertyValues } from 'lit'
import { property } from 'lit/decorators.js'
import { live } from 'lit/directives/live.js'
import { ClassInfo, classMap } from 'lit/directives/class-map.js'
import UiDialog from '../../../md/dialog/internals/Dialog.js'
import type Input from '../../../md/input/Input.js'
import '../../../md/text-field/ui-filled-text-field.js'
import {
  DeleteCookieStep,
  type IDeleteCookieStep,
} from '@api-client/core/models/http-flows/steps/data/DeleteCookieStep.js'

/**
 * A dialog used by the Flow builder to configure the Delete Cookie action.
 */
export default class DeleteCookieAction extends UiDialog {
  @property({ type: Object }) accessor step: IDeleteCookieStep | undefined

  override dialogValue: IDeleteCookieStep = new DeleteCookieStep().toJSON()

  constructor() {
    super()
    this.dismissLabel = 'Cancel'
    this.confirmLabel = 'Save'
  }

  override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('step')) {
      this.setupDialogValue()
    }
    super.willUpdate(cp)
  }

  protected setupDialogValue(): void {
    const { step } = this
    if (!step) {
      this.dialogValue = new DeleteCookieStep().toJSON()
    } else {
      this.dialogValue = new DeleteCookieStep(step).toJSON()
    }
  }

  protected handleUrlChange(e: Event): void {
    const input = e.target as Input
    this.dialogValue.url = input.value
  }

  protected handleNameChange(e: Event): void {
    const input = e.target as Input
    this.dialogValue.name = input.value
  }

  override renderIcon(): TemplateResult {
    const classes: ClassInfo = {
      'icon': true,
      'with-icon': true,
    }
    return html`
      <div class="${classMap(classes)}" part="icon"><ui-icon icon="tune" role="presentation"></ui-icon></div>
    `
  }

  override renderTitle(): TemplateResult {
    const classes: ClassInfo = {
      'title': true,
      'with-title': true,
    }
    return html` <div class="${classMap(classes)}" part="title"><span>Configure Delete Cookie Action</span></div> `
  }

  override renderBody(): TemplateResult {
    const { name = '', url = '' } = this.dialogValue

    return html`
      <div class="content">
        <div class="param-row">
          <ui-filled-text-field
            name="name"
            label="Cookie name"
            type="text"
            .value="${live(name)}"
            @change="${this.handleNameChange}"
            class="input"
            supportingText="Leave empty to delete all cookies for the URL."
          ></ui-filled-text-field>
        </div>
        <div class="param-row">
          <ui-filled-text-field
            name="url"
            label="Cookie URL"
            type="url"
            .value="${live(url)}"
            @change="${this.handleUrlChange}"
            class="input"
            supportingText="When the URL is not set then the request URL is used."
          ></ui-filled-text-field>
        </div>
      </div>
    `
  }
}
