import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-icon-picker";
import "../../../../components/input/ha-input";
import "../../../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import type { InputDateTime } from "../../../../data/input_datetime";
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";

@customElement("ha-input_datetime-form")
class HaInputDateTimeForm extends LitElement {
  @property({ attribute: false }) public hass!: HomeAssistant;

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

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

  private _item?: InputDateTime;

  @state() private _name!: string;

  @state() private _icon!: string;

  @state() private _mode!: "date" | "time" | "datetime";

  @query("[dialogInitialFocus]") private _focusElement?: HTMLElement;

  set item(item: InputDateTime) {
    this._item = item;
    if (item) {
      this._name = item.name || "";
      this._icon = item.icon || "";
      this._mode =
        item.has_time && item.has_date
          ? "datetime"
          : item.has_time
            ? "time"
            : "date";
      this._item.has_date =
        !item.has_date && !item.has_time ? true : item.has_date;
    } else {
      this._name = "";
      this._icon = "";
      this._mode = "date";
    }
  }

  public focus() {
    this.updateComplete.then(() => this._focusElement?.focus());
  }

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

    return html`
      <div class="form">
        <ha-input
          .value=${this._name}
          .configValue=${"name"}
          @input=${this._valueChanged}
          .label=${this.hass!.localize(
            "ui.dialogs.helper_settings.generic.name"
          )}
          auto-validate
          required
          .validationMessage=${this.hass!.localize(
            "ui.dialogs.helper_settings.required_error_msg"
          )}
          dialogInitialFocus
          .disabled=${this.disabled}
        ></ha-input>
        <ha-icon-picker
          .hass=${this.hass}
          .value=${this._icon}
          .configValue=${"icon"}
          @value-changed=${this._valueChanged}
          .label=${this.hass!.localize(
            "ui.dialogs.helper_settings.generic.icon"
          )}
          .disabled=${this.disabled}
        ></ha-icon-picker>
        <ha-radio-group
          .label=${this.hass.localize(
            "ui.dialogs.helper_settings.input_datetime.mode"
          )}
          .value=${this._mode}
          .disabled=${this.disabled}
          name="mode"
          @change=${this._modeChanged}
        >
          <ha-radio-option value="date">
            ${this.hass.localize(
              "ui.dialogs.helper_settings.input_datetime.date"
            )}
          </ha-radio-option>
          <ha-radio-option value="time">
            ${this.hass.localize(
              "ui.dialogs.helper_settings.input_datetime.time"
            )}
          </ha-radio-option>
          <ha-radio-option value="datetime">
            ${this.hass.localize(
              "ui.dialogs.helper_settings.input_datetime.datetime"
            )}
          </ha-radio-option>
        </ha-radio-group>
      </div>
    `;
  }

  private _modeChanged(ev: Event) {
    const mode = String((ev.currentTarget as HaRadioGroup).value);
    fireEvent(this, "value-changed", {
      value: {
        ...this._item,
        has_time: ["time", "datetime"].includes(mode),
        has_date: ["date", "datetime"].includes(mode),
      },
    });
  }

  private _valueChanged(ev: CustomEvent) {
    if (!this.new && !this._item) {
      return;
    }
    ev.stopPropagation();
    const configValue = (ev.target as any).configValue;
    const value = ev.detail?.value || (ev.target as any).value;
    if (this[`_${configValue}`] === value) {
      return;
    }
    const newValue = { ...this._item };
    if (!value) {
      delete newValue[configValue];
    } else {
      newValue[configValue] = value;
    }
    fireEvent(this, "value-changed", {
      value: newValue,
    });
  }

  static get styles(): CSSResultGroup {
    return [
      haStyle,
      css`
        .form {
          color: var(--primary-text-color);
        }
        .row {
          padding: var(--ha-space-4) 0;
        }
        ha-input {
          margin: var(--ha-space-2) 0;
        }
        ha-radio-group {
          margin-top: var(--ha-space-5);
        }
      `,
    ];
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "ha-input_datetime-form": HaInputDateTimeForm;
  }
}
