import {
  mdiAppleKeyboardCommand,
  mdiCommentEditOutline,
  mdiDelete,
  mdiPlaylistEdit,
} from "@mdi/js";
import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HaDropdownSelectEvent } from "../../../../components/ha-dropdown";
import "../../../../components/ha-dropdown-item";
import type { ScriptFieldSidebarConfig } from "../../../../data/automation";
import type { HomeAssistant } from "../../../../types";
import { isMac } from "../../../../util/is_mac";
import "../../script/ha-script-field-editor";
import type HaAutomationConditionEditor from "../action/ha-automation-action-editor";
import "../ha-automation-note";
import { overflowStyles, sidebarEditorStyles } from "../styles";
import "./ha-automation-sidebar-card";

@customElement("ha-automation-sidebar-script-field")
export default class HaAutomationSidebarScriptField extends LitElement {
  @property({ attribute: false }) public hass!: HomeAssistant;

  @property({ attribute: false }) public config!: ScriptFieldSidebarConfig;

  @property({ type: Boolean, attribute: "wide" }) public isWide = false;

  @property({ type: Boolean }) public disabled = false;

  @property({ type: Boolean, attribute: "yaml-mode" }) public yamlMode = false;

  @property({ type: Boolean }) public narrow = false;

  @property({ type: Number, attribute: "sidebar-key" })
  public sidebarKey?: number;

  @state() private _warnings?: string[];

  @query(".sidebar-editor")
  public editor?: HaAutomationConditionEditor;

  protected willUpdate(changedProperties: PropertyValues<this>) {
    if (changedProperties.has("config")) {
      this._warnings = undefined;
      if (this.config) {
        this.yamlMode = this.config.yamlMode;
        if (this.yamlMode) {
          this.editor?.yamlEditor?.setValue(this.config.config);
        }
      }
    }
  }

  protected render() {
    const title = this.hass.localize(
      "ui.panel.config.script.editor.field.label"
    );

    return html`<ha-automation-sidebar-card
      .hass=${this.hass}
      .isWide=${this.isWide}
      .yamlMode=${this.yamlMode}
      .warnings=${this._warnings}
      .narrow=${this.narrow}
      @wa-select=${this._handleDropdownSelect}
    >
      <span slot="title">${title}</span>
      <ha-dropdown-item slot="menu-items" value="edit_note">
        <ha-svg-icon slot="icon" .path=${mdiCommentEditOutline}></ha-svg-icon>
        <div class="overflow-label">
          ${this.hass.localize(
            `ui.panel.config.automation.editor.note.${this.config.config.field.description ? "edit" : "add"}`
          )}
          <span class="shortcut-placeholder ${isMac ? "mac" : ""}"></span>
        </div>
      </ha-dropdown-item>
      <ha-dropdown-item
        slot="menu-items"
        value="toggle_yaml_mode"
        .disabled=${!!this._warnings}
      >
        <ha-svg-icon slot="icon" .path=${mdiPlaylistEdit}></ha-svg-icon>
        <div class="overflow-label">
          ${this.hass.localize(
            `ui.panel.config.automation.editor.edit_${!this.yamlMode ? "yaml" : "ui"}`
          )}
          <span class="shortcut-placeholder ${isMac ? "mac" : ""}"></span>
        </div>
      </ha-dropdown-item>
      <ha-dropdown-item
        slot="menu-items"
        value="delete"
        .disabled=${this.disabled}
        variant="danger"
      >
        <ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
        <div class="overflow-label">
          ${this.hass.localize(
            "ui.panel.config.automation.editor.actions.delete"
          )}
          ${
            !this.narrow
              ? html`<span class="shortcut">
                  <span
                    >${
                      isMac
                        ? html`<ha-svg-icon
                            .path=${mdiAppleKeyboardCommand}
                          ></ha-svg-icon>`
                        : this.hass.localize(
                            "ui.panel.config.automation.editor.ctrl"
                          )
                    }</span
                  >
                  <span>+</span>
                  <span
                    >${this.hass.localize(
                      "ui.panel.config.automation.editor.del"
                    )}</span
                  >
                </span>`
              : nothing
          }
        </div>
      </ha-dropdown-item>
      ${keyed(
        this.sidebarKey,
        html`<ha-script-field-editor
          class="sidebar-editor"
          .hass=${this.hass}
          .field=${this.config.config.field}
          .key=${this.config.config.key}
          .excludeKeys=${this.config.config.excludeKeys}
          .disabled=${this.disabled}
          .yamlMode=${this.yamlMode}
          @value-changed=${this._valueChangedSidebar}
          @yaml-changed=${this._yamlChangedSidebar}
        ></ha-script-field-editor>`
      )}
      ${
        this.config.config.field.description?.trim() && !this.yamlMode
          ? html`<ha-automation-note
              @edit-note=${this.config.editNote}
              .note=${this.config.config.field.description}
            ></ha-automation-note>`
          : nothing
      }
    </ha-automation-sidebar-card>`;
  }

  private _valueChangedSidebar(ev: CustomEvent) {
    ev.stopPropagation();

    this.config?.save?.({
      ...this.config.config.field,
      key: ev.detail.value.key ?? this.config.config.key,
      ...ev.detail.value,
    });

    if (this.config) {
      fireEvent(this, "value-changed", {
        value: {
          ...this.config,
          config: {
            field: ev.detail.value,
            key: ev.detail.value.key ?? this.config.config.key,
            excludeKeys: this.config.config.excludeKeys,
          },
        },
      });
    }
  }

  private _yamlChangedSidebar(ev: CustomEvent) {
    ev.stopPropagation();

    this.config?.save?.(ev.detail.value);
  }

  private _toggleYamlMode = () => {
    fireEvent(this, "toggle-yaml-mode");
  };

  private _handleDropdownSelect(ev: HaDropdownSelectEvent) {
    const action = ev.detail?.item?.value;

    if (!action) {
      return;
    }

    switch (action) {
      case "toggle_yaml_mode":
        this._toggleYamlMode();
        break;
      case "edit_note":
        this.config.editNote();
        break;
      case "delete":
        this.config.delete();
        break;
    }
  }

  static styles = [sidebarEditorStyles, overflowStyles];
}

declare global {
  interface HTMLElementTagNameMap {
    "ha-automation-sidebar-script-field": HaAutomationSidebarScriptField;
  }
}
