import "@home-assistant/webawesome/dist/components/divider/divider";
import {
  mdiContentCopy,
  mdiContentCut,
  mdiDelete,
  mdiDotsVertical,
  mdiPencil,
  mdiPlusCircleMultipleOutline,
} from "@mdi/js";
import deepClone from "deep-clone-simple";
import type { CSSResultGroup, TemplateResult } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { storage } from "../../../common/decorators/storage";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-icon-button";
import "../../../components/ha-svg-icon";
import {
  ensureBadgeConfig,
  type LovelaceBadgeConfig,
} from "../../../data/lovelace/config/badge";
import { haStyle } from "../../../resources/styles";
import { showEditBadgeDialog } from "../editor/badge-editor/show-edit-badge-dialog";
import type { LovelaceCardPath } from "../editor/lovelace-path";
import {
  findLovelaceItems,
  getLovelaceContainerPath,
  parseLovelaceCardPath,
} from "../editor/lovelace-path";
import type { Lovelace } from "../types";

@customElement("hui-badge-edit-mode")
export class HuiBadgeEditMode extends LitElement {
  @property({ attribute: false }) public lovelace!: Lovelace;

  @property({ type: Array }) public path!: LovelaceCardPath;

  @property({ attribute: "hidden-overlay", type: Boolean })
  public hiddenOverlay = false;

  @state()
  @consumeLocalize()
  private _localize!: LocalizeFunc;

  @state()
  public _menuOpened = false;

  @state()
  public _hover = false;

  @state()
  public _focused = false;

  @storage({
    key: "dashboardBadgeClipboard",
    state: false,
    subscribe: false,
    storage: "sessionStorage",
  })
  protected _clipboard?: string | Partial<LovelaceBadgeConfig>;

  private get _badges() {
    const containerPath = getLovelaceContainerPath(this.path!);
    return findLovelaceItems("badges", this.lovelace!.config, containerPath)!;
  }

  private _touchStarted = false;

  protected firstUpdated(): void {
    this.addEventListener("focus", () => {
      this._focused = true;
    });
    this.addEventListener("blur", () => {
      this._focused = false;
    });
    this.addEventListener("touchstart", () => {
      this._touchStarted = true;
    });
    this.addEventListener("touchend", () => {
      setTimeout(() => {
        this._touchStarted = false;
      }, 10);
    });
    this.addEventListener("mouseenter", () => {
      if (this._touchStarted) return;
      this._hover = true;
    });
    this.addEventListener("mouseleave", () => {
      this._hover = false;
    });
    this.addEventListener("click", () => {
      this._hover = true;
      document.addEventListener("click", this._documentClicked);
    });
  }

  disconnectedCallback(): void {
    super.disconnectedCallback();
    document.removeEventListener("click", this._documentClicked);
  }

  private _documentClicked = (ev) => {
    this._hover = ev.composedPath().includes(this);
    document.removeEventListener("click", this._documentClicked);
  };

  protected render(): TemplateResult {
    const showOverlay =
      (this._hover || this._menuOpened || this._focused) && !this.hiddenOverlay;

    return html`
      <div class="badge-wrapper" inert><slot></slot></div>
      <div class="badge-overlay ${classMap({ visible: showOverlay })}">
        <div
          class="edit"
          @click=${this._handleOverlayClick}
          @keydown=${this._handleOverlayClick}
          tabindex="0"
        >
          <div class="edit-overlay"></div>
          <ha-svg-icon class="edit" .path=${mdiPencil}> </ha-svg-icon>
        </div>
        <ha-dropdown
          class="more"
          placement="bottom-end"
          @wa-select=${this._handleAction}
          @opened=${this._handleOpened}
          @closed=${this._handleClosed}
        >
          <ha-icon-button slot="trigger" .path=${mdiDotsVertical}>
          </ha-icon-button>
          <ha-dropdown-item value="edit">
            <ha-svg-icon slot="icon" .path=${mdiPencil}></ha-svg-icon>
            ${this._localize("ui.panel.lovelace.editor.edit_card.edit")}
          </ha-dropdown-item>
          <ha-dropdown-item value="duplicate">
            <ha-svg-icon
              slot="icon"
              .path=${mdiPlusCircleMultipleOutline}
            ></ha-svg-icon>
            ${this._localize("ui.panel.lovelace.editor.edit_card.duplicate")}
          </ha-dropdown-item>
          <ha-dropdown-item value="copy">
            <ha-svg-icon slot="icon" .path=${mdiContentCopy}></ha-svg-icon>
            ${this._localize("ui.panel.lovelace.editor.edit_card.copy")}
          </ha-dropdown-item>
          <ha-dropdown-item value="cut">
            <ha-svg-icon slot="icon" .path=${mdiContentCut}></ha-svg-icon>
            ${this._localize("ui.panel.lovelace.editor.edit_card.cut")}
          </ha-dropdown-item>
          <wa-divider></wa-divider>
          <ha-dropdown-item value="delete" variant="danger">
            ${this._localize("ui.panel.lovelace.editor.edit_card.delete")}
            <ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
          </ha-dropdown-item>
        </ha-dropdown>
      </div>
    `;
  }

  private _handleOpened() {
    this._menuOpened = true;
  }

  private _handleClosed() {
    this._menuOpened = false;
  }

  private _handleOverlayClick(ev): void {
    if (ev.defaultPrevented) {
      return;
    }
    if (ev.type === "keydown" && ev.key !== "Enter" && ev.key !== " ") {
      return;
    }
    ev.preventDefault();
    ev.stopPropagation();
    this._editBadge();
  }

  private _handleAction(ev: HaDropdownSelectEvent) {
    const value = ev.detail.item.value;
    switch (value) {
      case "edit":
        this._editBadge();
        break;
      case "duplicate":
        this._duplicateBadge();
        break;
      case "copy":
        this._copyBadge();
        break;
      case "cut":
        this._cutBadge();
        break;
      case "delete":
        this._deleteBadge();
        break;
    }
  }

  private _cutBadge(): void {
    this._copyBadge();
    fireEvent(this, "ll-delete-badge", { path: this.path!, silent: true });
  }

  private _copyBadge(): void {
    const { cardIndex } = parseLovelaceCardPath(this.path!);
    const cardConfig = this._badges[cardIndex];
    this._clipboard = deepClone(cardConfig);
  }

  private _duplicateBadge(): void {
    const { cardIndex } = parseLovelaceCardPath(this.path!);
    const containerPath = getLovelaceContainerPath(this.path!);
    const badgeConfig = ensureBadgeConfig(this._badges![cardIndex]);
    showEditBadgeDialog(this, {
      lovelaceConfig: this.lovelace!.config,
      saveConfig: this.lovelace!.saveConfig,
      path: containerPath as [number],
      badgeConfig,
    });
  }

  private _editBadge(): void {
    fireEvent(this, "ll-edit-badge", { path: this.path! });
  }

  private _deleteBadge(): void {
    fireEvent(this, "ll-delete-badge", { path: this.path!, silent: false });
  }

  static get styles(): CSSResultGroup {
    return [
      haStyle,
      css`
        .badge-overlay {
          position: absolute;
          opacity: 0;
          pointer-events: none;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: opacity 180ms ease-in-out;
        }

        .badge-overlay.visible {
          opacity: 1;
          pointer-events: auto;
        }

        .badge-wrapper {
          position: relative;
          height: 100%;
          z-index: 0;
        }

        .edit {
          outline: none !important;
          cursor: pointer;
          position: absolute;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: var(
            --ha-card-border-radius,
            var(--ha-border-radius-lg)
          );
          z-index: 0;
        }
        .edit-overlay {
          position: absolute;
          inset: 0;
          opacity: 0.8;
          background-color: var(--primary-background-color);
          border-radius: var(
            --ha-card-border-radius,
            var(--ha-border-radius-lg)
          );
          z-index: 0;
        }
        .edit ha-svg-icon {
          display: flex;
          position: relative;
          color: var(--primary-text-color);
          border-radius: var(--ha-border-radius-circle);
          padding: 4px;
          background: var(--secondary-background-color);
          --mdc-icon-size: 16px;
        }
        .more ha-icon-button {
          position: absolute;
          right: -8px;
          top: -8px;
          inset-inline-end: -10px;
          inset-inline-start: initial;
        }
        .more ha-icon-button {
          cursor: pointer;
          border-radius: var(--ha-border-radius-circle);
          background: var(--secondary-background-color);
          --ha-icon-button-size: 24px;
          --mdc-icon-size: 16px;
        }
      `,
    ];
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "hui-badge-edit-mode": HuiBadgeEditMode;
  }
}
