import { consume } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../components/ha-alert";
import "../../../components/ha-button";
import "../../../components/ha-markdown";
import "../../../components/input/ha-input";
import { apiContext } from "../../../data/context";
import type { HomeAssistantApi } from "../../../types";

@customElement("more-info-configurator")
export class MoreInfoConfigurator extends LitElement {
  @property({ attribute: false }) public stateObj?: HassEntity;

  @state() private _isConfiguring = false;

  @state()
  @consume({ context: apiContext, subscribe: true })
  private _api!: HomeAssistantApi;

  private _fieldInput: Record<string, unknown> = {};

  protected render() {
    if (this.stateObj?.state !== "configure") {
      return nothing;
    }

    return html`
      <div class="container">
        <ha-markdown
          breaks
          .content=${this.stateObj.attributes.description}
        ></ha-markdown>

        ${this.stateObj.attributes.errors
          ? html`<ha-alert alert-type="error">
              ${this.stateObj.attributes.errors}
            </ha-alert>`
          : nothing}
        ${this.stateObj.attributes.fields.map(
          (field) =>
            html`<ha-input
              .label=${field.name}
              .name=${field.id}
              .type=${field.type}
              @change=${this._fieldChanged}
            ></ha-input>`
        )}
        ${this.stateObj.attributes.submit_caption
          ? html`<p class="submit">
              <ha-button
                .disabled=${this._isConfiguring}
                @click=${this._submitClicked}
                .loading=${this._isConfiguring}
              >
                ${this.stateObj.attributes.submit_caption}
              </ha-button>
            </p>`
          : nothing}
      </div>
    `;
  }

  private _fieldChanged(ev) {
    const el = ev.target;
    this._fieldInput[el.name] = el.value;
  }

  private _submitClicked() {
    const data = {
      configure_id: this.stateObj!.attributes.configure_id,
      fields: this._fieldInput,
    };

    this._isConfiguring = true;

    this._api.callService("configurator", "configure", data).then(
      () => {
        this._isConfiguring = false;
      },
      () => {
        this._isConfiguring = false;
      }
    );
  }

  static styles = css`
    .container {
      display: flex;
      flex-direction: column;
    }
    p {
      margin: var(--ha-space-2) 0;
    }

    a {
      color: var(--primary-color);
    }

    p > img {
      max-width: 100%;
    }

    p.center {
      text-align: center;
    }

    p.submit {
      text-align: center;
      height: 41px;
    }
  `;
}

declare global {
  interface HTMLElementTagNameMap {
    "more-info-configurator": MoreInfoConfigurator;
  }
}
