import { consume } from "@lit/context";
import type { TemplateResult, PropertyValues } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { transform } from "../../common/decorators/transform";
import { stateColorCss } from "../../common/entity/state_color";
import "../../components/ha-control-slider";
import {
  apiContext,
  formattersContext,
  internationalizationContext,
} from "../../data/context";
import type { CoverEntity } from "../../data/cover";
import { UNAVAILABLE } from "../../data/entity/entity";
import { DOMAIN_ATTRIBUTES_UNITS } from "../../data/entity/entity_attributes";
import type { FrontendLocaleData } from "../../data/translation";
import type {
  HomeAssistantApi,
  HomeAssistantFormatters,
  HomeAssistantInternationalization,
} from "../../types";

@customElement("ha-state-control-valve-position")
export class HaStateControlValvePosition extends LitElement {
  @state()
  @consume({ context: apiContext, subscribe: true })
  private _api!: HomeAssistantApi;

  @state()
  @consume({ context: formattersContext, subscribe: true })
  private _formatters!: HomeAssistantFormatters;

  @state()
  @consume({ context: internationalizationContext, subscribe: true })
  @transform<HomeAssistantInternationalization, FrontendLocaleData>({
    transformer: ({ locale }) => locale,
  })
  private _locale!: FrontendLocaleData;

  @property({ attribute: false }) public stateObj!: CoverEntity;

  @state() value?: number;

  protected updated(changedProp: PropertyValues<this>): void {
    if (changedProp.has("stateObj")) {
      const currentPosition = this.stateObj?.attributes.current_position;
      this.value =
        currentPosition != null ? Math.round(currentPosition) : undefined;
    }
  }

  private _valueChanged(ev: HASSDomEvent<HASSDomEvents["value-changed"]>) {
    const { value } = ev.detail;
    if (typeof value !== "number" || isNaN(value)) return;

    this._api.callService("valve", "set_valve_position", {
      entity_id: this.stateObj!.entity_id,
      position: value,
    });
  }

  protected render(): TemplateResult {
    const color = stateColorCss(this.stateObj);

    return html`
      <ha-control-slider
        touch-action="none"
        vertical
        .value=${this.value}
        min="0"
        max="100"
        show-handle
        @value-changed=${this._valueChanged}
        .label=${this._formatters.formatEntityAttributeName(
          this.stateObj,
          "current_position"
        )}
        style=${styleMap({
          "--control-slider-color": color,
          "--control-slider-background": color,
        })}
        .disabled=${this.stateObj.state === UNAVAILABLE}
        .unit=${DOMAIN_ATTRIBUTES_UNITS.valve.current_position}
        .locale=${this._locale}
      >
      </ha-control-slider>
    `;
  }

  static styles = css`
    ha-control-slider {
      height: 45vh;
      max-height: 320px;
      min-height: 200px;
      --control-slider-thickness: 130px;
      --control-slider-border-radius: var(--ha-border-radius-6xl);
      --control-slider-color: var(--primary-color);
      --control-slider-background: var(--disabled-color);
      --control-slider-background-opacity: 0.2;
      --control-slider-tooltip-font-size: var(--ha-font-size-xl);
    }
  `;
}

declare global {
  interface HTMLElementTagNameMap {
    "ha-state-control-valve-position": HaStateControlValvePosition;
  }
}
