import { mdiHelpCircleOutline } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../../common/dom/fire_event";
import { isEmptyEntityDomainFilter } from "../../../common/entity/entity_domain_filter";
import "../../../components/ha-alert";
import "../../../components/ha-card";
import "../../../components/ha-button";
import "../../../components/ha-md-list-item";
import "../../../components/ha-switch";
import type { HaSwitch } from "../../../components/ha-switch";
import "../../../components/input/ha-input";
import type { HaInput } from "../../../components/input/ha-input";
import type { CloudStatusLoggedIn } from "../../../data/cloud";
import { updateCloudPref } from "../../../data/cloud";
import type { ExposeEntitySettings } from "../../../data/expose";
import {
  getExposeNewEntities,
  setExposeNewEntities,
} from "../../../data/expose";
import type { HomeAssistant } from "../../../types";
import { showSaveSuccessToast } from "../../../util/toast-saved-success";
import "../../../components/voice-assistant-brand-icon";

@customElement("cloud-google-pref")
export class CloudGooglePref extends LitElement {
  @property({ attribute: false }) public hass!: HomeAssistant;

  @property({ attribute: false }) public exposedEntities?: Record<
    string,
    ExposeEntitySettings
  >;

  @property({ attribute: false }) public cloudStatus?: CloudStatusLoggedIn;

  @state() private _exposeNew?: boolean;

  protected willUpdate() {
    if (!this.hasUpdated) {
      getExposeNewEntities(this.hass, "cloud.google_assistant").then(
        (value) => {
          this._exposeNew = value.expose_new;
        }
      );
    }
  }

  private _exposedEntitiesCount = memoizeOne(
    (exposedEntities: Record<string, ExposeEntitySettings>) =>
      Object.entries(exposedEntities).filter(
        ([entityId, expose]) =>
          expose["cloud.google_assistant"] && entityId in this.hass.states
      ).length
  );

  protected render() {
    if (!this.cloudStatus) {
      return nothing;
    }

    const google_registered = this.cloudStatus.google_registered;
    const { google_enabled, google_report_state, google_secure_devices_pin } =
      this.cloudStatus.prefs;

    const manualConfig = !isEmptyEntityDomainFilter(
      this.cloudStatus.google_entities
    );

    return html`
      <ha-card outlined>
        <h1 class="card-header">
          <voice-assistant-brand-icon
            .voiceAssistantId=${"cloud.google_assistant"}
          >
          </voice-assistant-brand-icon
          >${this.hass.localize("ui.panel.config.cloud.account.google.title")}
        </h1>
        <div class="header-actions">
          <ha-icon-button
            .label=${this.hass.localize(
              "ui.panel.config.cloud.account.google.link_learn_how_it_works"
            )}
            .path=${mdiHelpCircleOutline}
            href="https://www.nabucasa.com/config/google_assistant/"
            target="_blank"
            rel="noreferrer"
            class="icon-link"
          ></ha-icon-button>
          <ha-switch
            .checked=${google_enabled}
            @change=${this._enabledToggleChanged}
          ></ha-switch>
        </div>
        <div class="card-content">
          <p>
            ${this.hass.localize("ui.panel.config.cloud.account.google.info")}
          </p>
          ${
            manualConfig
              ? html`<ha-alert alert-type="warning">
                  ${this.hass.localize(
                    "ui.panel.config.cloud.account.google.manual_config"
                  )}
                </ha-alert>`
              : nothing
          }
          ${
            !google_enabled
              ? nothing
              : html`
                  ${
                    !google_registered
                      ? html`
                          <ha-alert
                            .title=${this.hass.localize(
                              "ui.panel.config.cloud.account.google.not_configured_title"
                            )}
                          >
                            ${this.hass.localize(
                              "ui.panel.config.cloud.account.google.not_configured_text"
                            )}

                            <ul>
                              <li>
                                <a
                                  href="https://www.nabucasa.com/config/google_assistant/"
                                  target="_blank"
                                  rel="noreferrer"
                                >
                                  ${this.hass.localize(
                                    "ui.panel.config.cloud.account.google.config_documentation"
                                  )}
                                </a>
                              </li>
                            </ul>
                          </ha-alert>
                        `
                      : nothing
                  }
                  <ha-md-list-item>
                    <span slot="headline"
                      >${this.hass!.localize(
                        "ui.panel.config.cloud.account.google.expose_new_entities"
                      )}</span
                    >
                    <span slot="supporting-text"
                      >${this.hass!.localize(
                        "ui.panel.config.cloud.account.google.expose_new_entities_info"
                      )}</span
                    >
                    <ha-switch
                      slot="end"
                      .checked=${this._exposeNew}
                      .disabled=${this._exposeNew === undefined}
                      @change=${this._exposeNewToggleChanged}
                    ></ha-switch>
                  </ha-md-list-item>
                  ${
                    google_registered
                      ? html`
                          ${
                            this.cloudStatus.http_use_ssl
                              ? html`
                                  <ha-alert
                                    alert-type="warning"
                                    .title=${this.hass.localize(
                                      "ui.panel.config.cloud.account.google.http_use_ssl_warning_title"
                                    )}
                                  >
                                    ${this.hass.localize(
                                      "ui.panel.config.cloud.account.google.http_use_ssl_warning_text"
                                    )}
                                    <a
                                      href="https://www.nabucasa.com/config/google_assistant/#local-communication"
                                      target="_blank"
                                      rel="noreferrer"
                                      >${this.hass.localize(
                                        "ui.panel.config.common.learn_more"
                                      )}</a
                                    >
                                  </ha-alert>
                                `
                              : nothing
                          }
                          <ha-md-list-item>
                            <span slot="headline"
                              >${this.hass!.localize(
                                "ui.panel.config.cloud.account.google.enable_state_reporting"
                              )}</span
                            >
                            <span slot="supporting-text"
                              >${this.hass!.localize(
                                "ui.panel.config.cloud.account.google.info_state_reporting"
                              )}</span
                            >
                            <ha-switch
                              slot="end"
                              .checked=${google_report_state}
                              @change=${this._reportToggleChanged}
                            ></ha-switch>
                          </ha-md-list-item>

                          <ha-md-list-item>
                            <span slot="headline"
                              >${this.hass.localize(
                                "ui.panel.config.cloud.account.google.security_devices"
                              )}</span
                            >
                            <span slot="supporting-text"
                              >${this.hass.localize(
                                "ui.panel.config.cloud.account.google.enter_pin_info"
                              )}</span
                            >
                            <ha-switch slot="end"></ha-switch>
                          </ha-md-list-item>

                          <ha-input
                            id="google_secure_devices_pin"
                            .label=${this.hass.localize(
                              "ui.panel.config.cloud.account.google.devices_pin"
                            )}
                            .placeholder=${this.hass.localize(
                              "ui.panel.config.cloud.account.google.enter_pin_hint"
                            )}
                            .value=${google_secure_devices_pin || ""}
                            @change=${this._pinChanged}
                          ></ha-input>
                        `
                      : nothing
                  }
                `
          }
        </div>
        ${
          google_enabled
            ? html`<div class="card-actions">
                <ha-button
                  appearance="plain"
                  size="s"
                  href="/config/voice-assistants/expose?assistants=cloud.google_assistant&historyBack"
                >
                  ${
                    manualConfig
                      ? this.hass!.localize(
                          "ui.panel.config.cloud.account.google.show_entities"
                        )
                      : this.hass.localize(
                          "ui.panel.config.cloud.account.google.exposed_entities",
                          {
                            number: this.exposedEntities
                              ? this._exposedEntitiesCount(this.exposedEntities)
                              : 0,
                          }
                        )
                  }
                </ha-button>
              </div>`
            : nothing
        }
      </ha-card>
    `;
  }

  private async _exposeNewToggleChanged(ev) {
    const toggle = ev.target as HaSwitch;
    if (this._exposeNew === undefined || this._exposeNew === toggle.checked) {
      return;
    }
    try {
      await setExposeNewEntities(
        this.hass,
        "cloud.google_assistant",
        toggle.checked
      );
    } catch (_err: any) {
      toggle.checked = !toggle.checked;
    }
  }

  private async _enabledToggleChanged(ev) {
    const toggle = ev.target as HaSwitch;
    try {
      await updateCloudPref(this.hass, { google_enabled: toggle.checked! });
      fireEvent(this, "ha-refresh-cloud-status");
    } catch (_err: any) {
      toggle.checked = !toggle.checked;
    }
  }

  private async _reportToggleChanged(ev) {
    const toggle = ev.target as HaSwitch;
    try {
      await updateCloudPref(this.hass, {
        google_report_state: toggle.checked!,
      });
      fireEvent(this, "ha-refresh-cloud-status");
    } catch (err: any) {
      alert(
        `Unable to ${toggle.checked ? "enable" : "disable"} report state. ${
          err.message
        }`
      );
      toggle.checked = !toggle.checked;
    }
  }

  private async _pinChanged(ev: InputEvent) {
    const input = ev.target as HaInput;
    try {
      await updateCloudPref(this.hass, {
        [input.id]: input.value || null,
      });
      showSaveSuccessToast(this, this.hass);
      fireEvent(this, "ha-refresh-cloud-status");
    } catch (err: any) {
      alert(
        `${this.hass.localize(
          "ui.panel.config.cloud.account.google.enter_pin_error"
        )} ${err.message}`
      );
      input.value = this.cloudStatus!.prefs.google_secure_devices_pin || "";
    }
  }

  static styles = css`
    a {
      color: var(--primary-color);
    }
    .header-actions {
      position: absolute;
      right: 24px;
      inset-inline-end: 24px;
      inset-inline-start: initial;
      top: 24px;
      display: flex;
      flex-direction: row;
    }
    .header-actions .icon-link {
      margin-top: -16px;
      margin-right: 8px;
      margin-inline-end: 8px;
      margin-inline-start: initial;
      direction: var(--direction);
      color: var(--secondary-text-color);
    }
    ha-md-list-item {
      --md-list-item-leading-space: 0;
      --md-list-item-trailing-space: 0;
      --md-item-overflow: visible;
    }
    ha-input {
      width: 250px;
      margin-top: 8px;
    }
    .card-actions {
      display: flex;
    }
    .card-actions a {
      text-decoration: none;
    }
    .warning {
      color: var(--error-color);
    }
    .card-header {
      display: flex;
      align-items: center;
    }
    voice-assistant-brand-icon {
      height: 28px;
      margin-right: 16px;
      margin-inline-end: 16px;
      margin-inline-start: initial;
    }
  `;
}

declare global {
  interface HTMLElementTagNameMap {
    "cloud-google-pref": CloudGooglePref;
  }
}
