import { mdiHelpCircleOutline } from "@mdi/js";
import type { PropertyValues } from "lit";
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 "../../../../../components/ha-checkbox";
import "../../../../../components/ha-selector/ha-selector";
import "../../../../../components/ha-settings-row";
import type { PlatformCondition } from "../../../../../data/automation";
import {
  getConditionDomain,
  getConditionObjectId,
  type ConditionDescription,
} from "../../../../../data/condition";
import type { IntegrationManifest } from "../../../../../data/integration";
import { fetchIntegrationManifest } from "../../../../../data/integration";
import type { TargetSelector } from "../../../../../data/selector";
import { getTargetEntityCount } from "../../../../../data/target";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";

const showOptionalToggle = (field: ConditionDescription["fields"][string]) =>
  field.selector &&
  !field.required &&
  !("boolean" in field.selector && field.default);

@customElement("ha-automation-condition-platform")
export class HaPlatformCondition extends LitElement {
  @property({ attribute: false }) public hass!: HomeAssistant;

  @property({ attribute: false }) public condition!: PlatformCondition;

  @property({ attribute: false }) public description?: ConditionDescription;

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

  @state() private _checkedKeys = new Set();

  @state() private _manifest?: IntegrationManifest;

  @state() private _resolvedTargetEntityCount?: number;

  public static get defaultConfig(): PlatformCondition {
    return { condition: "" };
  }

  protected willUpdate(changedProperties: PropertyValues<this>) {
    super.willUpdate(changedProperties);
    if (!this.hasUpdated) {
      this.hass.loadBackendTranslation("conditions");
      this.hass.loadBackendTranslation("selector");
    }
    if (!changedProperties.has("condition")) {
      return;
    }
    const oldValue = changedProperties.get("condition") as
      | undefined
      | this["condition"];

    // Fetch the manifest if we have a condition selected and the condition domain changed.
    // If no condition is selected, clear the manifest.
    if (this.condition?.condition) {
      const domain = getConditionDomain(this.condition.condition);

      const oldDomain = getConditionDomain(oldValue?.condition || "");

      if (domain !== oldDomain) {
        this._fetchManifest(domain);
      }
    } else {
      this._manifest = undefined;
    }

    if (
      this.condition &&
      oldValue?.condition !== this.condition.condition &&
      this.description?.fields
    ) {
      const hadOptions = "options" in this.condition;
      const updatedOptions = this.condition.options
        ? { ...this.condition.options }
        : {};
      const loadDefaults = !hadOptions;
      let updatedDefaultValue = false;
      // Set mandatory bools without a default value to false
      Object.entries(this.description.fields).forEach(([key, field]) => {
        if (
          field.selector &&
          field.required &&
          field.default === undefined &&
          "boolean" in field.selector &&
          updatedOptions[key] === undefined
        ) {
          updatedDefaultValue = true;
          updatedOptions[key] = false;
        } else if (
          loadDefaults &&
          field.selector &&
          field.default !== undefined &&
          updatedOptions[key] === undefined &&
          !(
            field.selector &&
            "automation_behavior" in field.selector &&
            this.description?.target &&
            !this.condition?.target
          )
        ) {
          updatedDefaultValue = true;
          updatedOptions[key] = field.default;
        }
      });
      if (!hadOptions || updatedDefaultValue) {
        fireEvent(this, "value-changed", {
          value: {
            ...this.condition,
            options: updatedOptions,
          },
        });
      }
    }

    if (oldValue?.target !== this.condition?.target) {
      this._updateResolvedTargetEntityCount(this.condition?.target);
    }
  }

  protected render() {
    const domain = getConditionDomain(this.condition.condition);
    const conditionName = getConditionObjectId(this.condition.condition);

    const description = this.hass.localize(
      `component.${domain}.conditions.${conditionName}.description`
    );

    const conditionDesc = this.description;

    const shouldRenderDataYaml = !conditionDesc?.fields;

    const hasOptional = Boolean(
      conditionDesc?.fields &&
      Object.values(conditionDesc.fields).some((field) =>
        showOptionalToggle(field)
      )
    );

    return html`
      <div class="description">
        ${description ? html`<p>${description}</p>` : nothing}
        ${this._manifest
          ? html`<a
              href=${this._manifest.is_built_in
                ? documentationUrl(
                    this.hass,
                    `/integrations/${this._manifest.domain}`
                  )
                : this._manifest.documentation}
              title=${this.hass.localize(
                "ui.components.service-control.integration_doc"
              )}
              target="_blank"
              rel="noreferrer"
            >
              <ha-icon-button
                .path=${mdiHelpCircleOutline}
                class="help-icon"
                .label=${this.hass.localize(
                  "ui.components.service-control.integration_doc"
                )}
              ></ha-icon-button>
            </a>`
          : nothing}
      </div>
      ${conditionDesc && "target" in conditionDesc
        ? html`<ha-settings-row narrow>
            <span slot="heading"
              >${this.hass.localize(
                "ui.components.service-control.target"
              )}</span
            >
            <ha-selector
              .hass=${this.hass}
              .selector=${this._targetSelector(conditionDesc.target)}
              .disabled=${this.disabled}
              @value-changed=${this._targetChanged}
              .value=${this.condition?.target}
            ></ha-selector
          ></ha-settings-row>`
        : nothing}
      ${shouldRenderDataYaml
        ? html`<ha-yaml-editor
            .label=${this.hass.localize(
              "ui.components.service-control.action_data"
            )}
            .name=${"data"}
            .readOnly=${this.disabled}
            .defaultValue=${this.condition?.options}
            @value-changed=${this._dataChanged}
          ></ha-yaml-editor>`
        : Object.entries(conditionDesc.fields).map(([fieldName, dataField]) =>
            this._renderField(
              fieldName,
              dataField,
              hasOptional,
              domain,
              conditionName
            )
          )}
    `;
  }

  private _targetSelector = memoizeOne(
    (targetSelector: TargetSelector["target"] | null | undefined) =>
      targetSelector ? { target: { ...targetSelector } } : { target: {} }
  );

  private _renderField = (
    fieldName: string,
    dataField: ConditionDescription["fields"][string],
    hasOptional: boolean,
    domain: string | undefined,
    conditionName: string | undefined
  ) => {
    const selector = dataField?.selector ?? { text: null };

    const showOptional = showOptionalToggle(dataField);

    if (!dataField.selector) {
      return nothing;
    }

    if (
      "automation_behavior" in selector &&
      this.description?.target &&
      (!this.condition?.target ||
        (this._resolvedTargetEntityCount !== undefined &&
          this._resolvedTargetEntityCount <= 1))
    ) {
      return nothing;
    }

    const description = this.hass.localize(
      `component.${domain}.conditions.${conditionName}.fields.${fieldName}.description`
    );

    return html`<ha-settings-row narrow>
      ${!showOptional
        ? hasOptional
          ? html`<div slot="prefix" class="checkbox-spacer"></div>`
          : nothing
        : html`<ha-checkbox
            .key=${fieldName}
            .checked=${this._checkedKeys.has(fieldName) ||
            (!!this.condition?.options &&
              this.condition.options[fieldName] !== undefined)}
            .disabled=${this.disabled}
            @change=${this._checkboxChanged}
            slot="prefix"
          ></ha-checkbox>`}
      <span
        slot="heading"
        class=${showOptional ? "clickable" : ""}
        @click=${showOptional ? this._toggleCheckbox : undefined}
        >${this.hass.localize(
          `component.${domain}.conditions.${conditionName}.fields.${fieldName}.name`
        ) || fieldName}</span
      >
      ${description
        ? html`<span
            class=${showOptional ? "clickable" : ""}
            @click=${showOptional ? this._toggleCheckbox : undefined}
            slot="description"
            >${description}</span
          >`
        : nothing}
      <ha-selector
        .disabled=${this.disabled ||
        (showOptional &&
          !this._checkedKeys.has(fieldName) &&
          (!this.condition?.options ||
            this.condition.options[fieldName] === undefined))}
        .hass=${this.hass}
        .selector=${selector}
        .context=${this._generateContext(dataField)}
        .key=${fieldName}
        @value-changed=${this._dataChanged}
        .value=${this.condition?.options
          ? this.condition.options[fieldName]
          : undefined}
        .placeholder=${dataField.default}
        .localizeValue=${this._localizeValueCallback}
        .required=${dataField.required}
      ></ha-selector>
    </ha-settings-row>`;
  };

  private _generateContext(
    field: ConditionDescription["fields"][string]
  ): Record<string, any> | undefined {
    if (!field.context) {
      return undefined;
    }

    const context: Record<string, any> = {};
    for (const [context_key, data_key] of Object.entries(field.context)) {
      if (data_key === "target" && this.description?.target) {
        context.target_selector = this._targetSelector(this.description.target);
      }
      context[context_key] =
        data_key === "target"
          ? this.condition.target
          : this.condition.options?.[data_key];
    }
    return context;
  }

  private _dataChanged(ev: CustomEvent) {
    ev.stopPropagation();
    if (ev.detail.isValid === false) {
      // Don't clear an object selector that returns invalid YAML
      return;
    }
    const key = (ev.currentTarget as any).key;
    const value = ev.detail.value;
    if (
      this.condition?.options?.[key] === value ||
      ((!this.condition?.options || !(key in this.condition.options)) &&
        (value === "" || value === undefined))
    ) {
      return;
    }

    const options = { ...this.condition?.options, [key]: value };

    if (
      value === "" ||
      value === undefined ||
      (typeof value === "object" && !Object.keys(value).length)
    ) {
      delete options[key];
    }

    fireEvent(this, "value-changed", {
      value: {
        ...this.condition,
        options,
      },
    });
  }

  private _targetChanged(ev: CustomEvent): void {
    ev.stopPropagation();
    fireEvent(this, "value-changed", {
      value: {
        ...this.condition,
        target: ev.detail.value,
      },
    });
  }

  private _toggleCheckbox(ev: Event) {
    const checkbox = (
      ev.currentTarget as HTMLElement
    )?.parentElement?.querySelector("ha-checkbox");
    checkbox?.click();
  }

  private _checkboxChanged(ev) {
    const checked = ev.currentTarget.checked;
    const key = ev.currentTarget.key;
    let options;

    if (checked) {
      this._checkedKeys.add(key);
      const field =
        this.description &&
        Object.entries(this.description).find(([k, _value]) => k === key)?.[1];
      let defaultValue = field?.default;

      if (
        defaultValue == null &&
        field?.selector &&
        "constant" in field.selector
      ) {
        defaultValue = field.selector.constant?.value;
      }

      if (
        defaultValue == null &&
        field?.selector &&
        "boolean" in field.selector
      ) {
        defaultValue = false;
      }

      if (defaultValue != null) {
        options = {
          ...this.condition?.options,
          [key]: defaultValue,
        };
      }
    } else {
      this._checkedKeys.delete(key);
      options = { ...this.condition?.options };
      delete options[key];
    }
    if (options) {
      fireEvent(this, "value-changed", {
        value: {
          ...this.condition,
          options,
        },
      });
    }
    this.requestUpdate("_checkedKeys");
  }

  private _localizeValueCallback = (key: string) => {
    if (!this.condition?.condition) {
      return "";
    }
    return this.hass.localize(
      `component.${getConditionDomain(this.condition.condition)}.selector.${key}`
    );
  };

  private async _fetchManifest(integration: string) {
    this._manifest = undefined;
    try {
      this._manifest = await fetchIntegrationManifest(this.hass, integration);
    } catch (_err: any) {
      // eslint-disable-next-line no-console
      console.log(`Unable to fetch integration manifest for ${integration}`);
      // Ignore if loading manifest fails. Probably bad JSON in manifest
    }
  }

  private _updateResolvedTargetEntityCount(
    target: PlatformCondition["target"]
  ) {
    this._resolvedTargetEntityCount = getTargetEntityCount(target);

    const behaviorFieldEntry = Object.entries(
      this.description?.fields ?? {}
    ).find(
      ([, field]) => field.selector && "automation_behavior" in field.selector
    );

    if (!behaviorFieldEntry) {
      return;
    }

    const [behaviorFieldName, behaviorField] = behaviorFieldEntry;

    if (
      target &&
      this._resolvedTargetEntityCount > 1 &&
      this.condition.options?.[behaviorFieldName] === undefined
    ) {
      const behaviorDefault = behaviorField.default;
      if (behaviorDefault !== undefined) {
        fireEvent(this, "value-changed", {
          value: {
            ...this.condition,
            options: {
              ...this.condition.options,
              [behaviorFieldName]: behaviorDefault,
            },
          },
        });
      }
    }
  }

  static styles = css`
    :host {
      display: block;
      margin: 0px calc(-1 * var(--ha-space-4));
    }
    ha-settings-row {
      padding: 0 var(--ha-space-4);
    }
    ha-settings-row[narrow] {
      padding-bottom: var(--ha-space-2);
    }
    ha-settings-row {
      --settings-row-content-width: 100%;
      --settings-row-prefix-display: contents;
      border-top: var(
        --service-control-items-border-top,
        1px solid var(--divider-color)
      );
    }
    ha-service-picker,
    ha-entity-picker,
    ha-yaml-editor {
      display: block;
      margin: 0 var(--ha-space-4);
    }
    ha-yaml-editor {
      padding: var(--ha-space-4) 0;
    }
    p {
      margin: 0 var(--ha-space-4);
      padding: var(--ha-space-4) 0;
    }
    :host([hide-picker]) p {
      padding-top: 0;
    }
    .checkbox-spacer {
      width: 32px;
    }
    .help-icon {
      color: var(--secondary-text-color);
    }
    .description {
      justify-content: space-between;
      display: flex;
      align-items: center;
      padding-right: 2px;
      padding-inline-end: 2px;
      padding-inline-start: initial;
    }
    .description p {
      direction: ltr;
    }
    .clickable {
      cursor: pointer;
    }
  `;
}

declare global {
  interface HTMLElementTagNameMap {
    "ha-automation-condition-platform": HaPlatformCondition;
  }
}
