import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/input/ha-input";
import "./ha-energy-upstream-device-picker";
import type { HaInput } from "../../../../components/input/ha-input";
import type { DeviceConsumptionEnergyPreference } from "../../../../data/energy";
import { energyStatisticHelpUrl } from "../../../../data/energy";
import {
  getStatisticLabel,
  getStatisticMetadata,
  isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy";

const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];

@customElement("dialog-energy-device-settings")
export class DialogEnergyDeviceSettings
  extends DirtyStateProviderMixin<DeviceConsumptionEnergyPreference | null>()(
    LitElement
  )
  implements HassDialog<EnergySettingsDeviceDialogParams>
{
  @property({ attribute: false }) public hass!: HomeAssistant;

  @state() private _params?: EnergySettingsDeviceDialogParams;

  @state() private _open = false;

  @state() private _device?: DeviceConsumptionEnergyPreference;

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

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

  @state() private _error?: string;

  private _excludeList?: string[];

  private _excludeListPower?: string[];

  private _possibleParents: DeviceConsumptionEnergyPreference[] = [];

  public async showDialog(
    params: EnergySettingsDeviceDialogParams
  ): Promise<void> {
    this._params = params;
    this._device = this._params.device;
    this._computePossibleParents();
    this._energy_units = (
      await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
    ).units;
    this._power_units = (
      await getSensorDeviceClassConvertibleUnits(this.hass, "power")
    ).units;
    this._excludeList = this._params.device_consumptions
      .map((entry) => entry.stat_consumption)
      .filter((id) => id !== this._device?.stat_consumption);
    this._excludeListPower = this._params.device_consumptions
      .map((entry) => entry.stat_rate)
      .filter((id) => id && id !== this._device?.stat_rate) as string[];

    this._open = true;
    this._initDirtyTracking({ type: "deep" }, this._device ?? null);
  }

  private _computePossibleParents() {
    if (!this._device || !this._params) {
      this._possibleParents = [];
      return;
    }
    const children: string[] = [];
    const devices = this._params.device_consumptions;
    function getChildren(stat) {
      devices.forEach((d) => {
        if (d.included_in_stat === stat) {
          children.push(d.stat_consumption);
          getChildren(d.stat_consumption);
        }
      });
    }
    getChildren(this._device.stat_consumption);
    this._possibleParents = this._params.device_consumptions.filter(
      (d) =>
        d.stat_consumption !== this._device!.stat_consumption &&
        d.stat_consumption !== this._params?.device?.stat_consumption &&
        !children.includes(d.stat_consumption)
    );
  }

  public closeDialog() {
    this._open = false;
    return true;
  }

  private _dialogClosed() {
    this._params = undefined;
    this._device = undefined;
    this._error = undefined;
    this._excludeList = undefined;
    fireEvent(this, "dialog-closed", { dialog: this.localName });
  }

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

    return html`
      <ha-dialog
        .open=${this._open}
        header-title=${this.hass.localize(
          "ui.panel.config.energy.device_consumption.dialog.header"
        )}
        .preventScrimClose=${this.isDirtyState}
        @closed=${this._dialogClosed}
      >
        ${this._error ? html`<p class="error">${this._error}</p>` : ""}

        <ha-statistic-picker
          .hass=${this.hass}
          .helpMissingEntityUrl=${energyStatisticHelpUrl}
          .includeUnitClass=${energyUnitClasses}
          .value=${this._device?.stat_consumption}
          .label=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.device_consumption_energy"
          )}
          .excludeStatistics=${this._excludeList}
          @value-changed=${this._statisticChanged}
          .helper=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
            { unit: this._energy_units?.join(", ") || "" }
          )}
          autofocus
        ></ha-statistic-picker>

        <ha-statistic-picker
          .hass=${this.hass}
          .includeUnitClass=${powerUnitClasses}
          .value=${this._device?.stat_rate}
          .label=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.device_consumption_power"
          )}
          .excludeStatistics=${this._excludeListPower}
          @value-changed=${this._powerStatisticChanged}
          .helper=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
            { unit: this._power_units?.join(", ") || "" }
          )}
        ></ha-statistic-picker>

        <ha-input
          .label=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.display_name"
          )}
          .disabled=${!this._device}
          .value=${this._device?.name || ""}
          .placeholder=${
            this._device
              ? getStatisticLabel(
                  this.hass,
                  this._device.stat_consumption,
                  this._params?.statsMetadata?.[this._device.stat_consumption]
                )
              : ""
          }
          @input=${this._nameChanged}
        >
        </ha-input>

        <ha-energy-upstream-device-picker
          .hass=${this.hass}
          .label=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.included_in_device"
          )}
          .helper=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.included_in_device_helper"
          )}
          .value=${this._device?.included_in_stat}
          .possibleParents=${this._possibleParents}
          .statsMetadata=${this._params.statsMetadata}
          .emptyLabel=${this.hass.localize(
            "ui.panel.config.energy.device_consumption.dialog.no_upstream_devices"
          )}
          .disabled=${!this._device}
          @value-changed=${this._parentChanged}
        ></ha-energy-upstream-device-picker>

        <ha-dialog-footer slot="footer">
          <ha-button
            appearance="plain"
            @click=${this.closeDialog}
            slot="secondaryAction"
          >
            ${this.hass.localize("ui.common.cancel")}
          </ha-button>
          <ha-button
            @click=${this._save}
            .disabled=${
              !this._device || (!!this._params?.device && !this.isDirtyState)
            }
            slot="primaryAction"
          >
            ${this.hass.localize("ui.common.save")}
          </ha-button>
        </ha-dialog-footer>
      </ha-dialog>
    `;
  }

  private async _statisticChanged(ev: ValueChangedEvent<string>) {
    if (!ev.detail.value) {
      this._device = undefined;
      this._updateDirtyState(this._device ?? null);
      return;
    }
    this._device = { stat_consumption: ev.detail.value };
    this._computePossibleParents();
    this._updateDirtyState(this._device);

    if (
      isExternalStatistic(ev.detail.value) &&
      this._params?.statsMetadata &&
      !(ev.detail.value in this._params.statsMetadata)
    ) {
      const [metadata] = await getStatisticMetadata(this.hass, [
        ev.detail.value,
      ]);
      if (metadata) {
        this._params.statsMetadata[ev.detail.value] = metadata;
        this.requestUpdate("_params");
      }
    }
  }

  private _powerStatisticChanged(ev: ValueChangedEvent<string>) {
    if (!this._device) {
      return;
    }
    const newDevice = {
      ...this._device,
      stat_rate: ev.detail.value,
    } as DeviceConsumptionEnergyPreference;
    if (!newDevice.stat_rate) {
      delete newDevice.stat_rate;
    }
    this._device = newDevice;
    this._updateDirtyState(this._device);
  }

  private _nameChanged(ev: InputEvent) {
    const newDevice = {
      ...this._device!,
      name: (ev.target as HaInput).value,
    } as DeviceConsumptionEnergyPreference;
    if (!newDevice.name) {
      delete newDevice.name;
    }
    this._device = newDevice;
    this._updateDirtyState(this._device);
  }

  private _parentChanged(ev: ValueChangedEvent<string>) {
    const newDevice = {
      ...this._device!,
      included_in_stat: ev.detail.value,
    } as DeviceConsumptionEnergyPreference;
    if (!newDevice.included_in_stat) {
      delete newDevice.included_in_stat;
    }
    this._device = newDevice;
    this._updateDirtyState(this._device);
  }

  private async _save() {
    try {
      await this._params!.saveCallback(this._device!);
      this._markDirtyStateClean();
      this.closeDialog();
    } catch (err: any) {
      this._error = err.message;
    }
  }

  static get styles(): CSSResultGroup {
    return [
      haStyleDialog,
      css`
        ha-statistic-picker {
          display: block;
          margin-bottom: var(--ha-space-2);
        }
        ha-statistic-picker {
          width: 100%;
        }
        ha-energy-upstream-device-picker {
          display: block;
          margin-top: var(--ha-space-4);
          width: 100%;
        }
        ha-input {
          margin-top: var(--ha-space-4);
          --ha-input-padding-bottom: 0;
          width: 100%;
        }
      `,
    ];
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "dialog-energy-device-settings": DialogEnergyDeviceSettings;
  }
}
