import { mdiPencil } from "@mdi/js";
import type { CSSResultGroup } 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/entity/ha-entities-picker";
import "../../../components/ha-button";
import "../../../components/ha-dialog";
import "../../../components/ha-dialog-footer";
import "../../../components/ha-icon-button";
import "../../../components/ha-picture-upload";
import type { HaPictureUpload } from "../../../components/ha-picture-upload";
import "../../../components/input/ha-input";
import "../../../components/item/ha-row-item";
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
import { adminChangeUsername } from "../../../data/auth";
import type { PersonMutableParams } from "../../../data/person";
import type { User } from "../../../data/user";
import {
  deleteUser,
  SYSTEM_GROUP_ID_ADMIN,
  SYSTEM_GROUP_ID_USER,
  updateUser,
} from "../../../data/user";
import {
  showAlertDialog,
  showConfirmationDialog,
  showPromptDialog,
} from "../../../dialogs/generic/show-dialog-box";
import type { CropOptions } from "../../../dialogs/image-cropper-dialog/show-image-cropper-dialog";
import type { HassDialog } from "../../../dialogs/make-dialog-manager";
import { haStyleDialog } from "../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import { documentationUrl } from "../../../util/documentation-url";
import { showAddUserDialog } from "../users/show-dialog-add-user";
import { showAdminChangePasswordDialog } from "../users/show-dialog-admin-change-password";
import type { PersonDetailDialogParams } from "./show-dialog-person-detail";

const includeDomains = ["device_tracker"];

const cropOptions: CropOptions = {
  round: true,
  quality: 0.75,
  aspectRatio: 1,
};

interface PersonFormState {
  name: string;
  picture: string | null;
  userId: string | undefined;
  deviceTrackers: string[];
  isAdmin: boolean | undefined;
  localOnly: boolean | undefined;
}

@customElement("dialog-person-detail")
class DialogPersonDetail
  extends DirtyStateProviderMixin<PersonFormState>()(LitElement)
  implements HassDialog
{
  @property({ attribute: false }) public hass!: HomeAssistant;

  @state() private _name!: string;

  @state() private _userId?: string;

  @state() private _user?: User;

  @state() private _isAdmin?: boolean;

  @state() private _localOnly?: boolean;

  @state() private _deviceTrackers!: string[];

  @state() private _picture!: string | null;

  @state() private _error?: string;

  @state() private _params?: PersonDetailDialogParams;

  @state() private _submitting = false;

  @state() private _personExists = false;

  @state() private _open = false;

  private _deviceTrackersAvailable = memoizeOne((hass) =>
    Object.keys(hass.states).some(
      (entityId) =>
        entityId.substr(0, entityId.indexOf(".")) === "device_tracker"
    )
  );

  public async showDialog(params: PersonDetailDialogParams): Promise<void> {
    this._params = params;
    this._error = undefined;
    if (this._params.entry) {
      this._personExists = true;
      this._name = this._params.entry.name || "";
      this._userId = this._params.entry.user_id || undefined;
      this._deviceTrackers = this._params.entry.device_trackers || [];
      this._picture = this._params.entry.picture || null;
      this._user = this._userId
        ? this._params.users?.find((user) => user.id === this._userId)
        : undefined;
      this._isAdmin = this._user?.group_ids.includes(SYSTEM_GROUP_ID_ADMIN);
      this._localOnly = this._user?.local_only;
    } else {
      this._personExists = false;
      this._name = "";
      this._userId = undefined;
      this._user = undefined;
      this._isAdmin = undefined;
      this._localOnly = undefined;
      this._deviceTrackers = [];
      this._picture = null;
    }
    this._open = true;
    this._initDirtyTracking({ type: "deep" }, this._currentState());
    await this.updateComplete;
  }

  private _currentState(): PersonFormState {
    return {
      name: this._name,
      picture: this._picture,
      userId: this._userId,
      deviceTrackers: this._deviceTrackers,
      isAdmin: this._isAdmin,
      localOnly: this._localOnly,
    };
  }

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

  private _dialogClosed() {
    // If we do not have a person ID yet (= person creation dialog was just cancelled), but
    // we already created a user ID for it, delete it now to not have it "free floating".
    if (!this._personExists && this._userId) {
      const callback = this._params?.refreshUsers;
      deleteUser(this.hass, this._userId).then(() => {
        callback?.();
      });
      this._userId = undefined;
    }
    this._params = undefined;
    fireEvent(this, "dialog-closed", { dialog: this.localName });
  }

  protected render() {
    if (!this._params) {
      return nothing;
    }
    const nameInvalid = this._name.trim() === "";
    return html`
      <ha-dialog
        .open=${this._open}
        .preventScrimClose=${this.isDirtyState}
        header-title=${
          this._params.entry
            ? this._params.entry.name
            : this.hass!.localize("ui.panel.config.person.detail.new_person")
        }
        @closed=${this._dialogClosed}
      >
        <div>
          ${this._error ? html` <div class="error">${this._error}</div> ` : ""}
          <div class="form">
            <ha-input
              autofocus
              .value=${this._name}
              @input=${this._nameChanged}
              label=${this.hass!.localize("ui.panel.config.person.detail.name")}
              .validationMessage=${this.hass!.localize(
                "ui.panel.config.person.detail.name_error_msg"
              )}
              required
            ></ha-input>

            <ha-picture-upload
              .hass=${this.hass}
              .value=${this._picture}
              crop
              select-media
              .cropOptions=${cropOptions}
              @change=${this._pictureChanged}
            ></ha-picture-upload>

            <ha-row-item>
              <span slot="headline"
                >${this.hass!.localize(
                  "ui.panel.config.person.detail.allow_login"
                )}</span
              >
              <span slot="supporting-text"
                >${this.hass!.localize(
                  "ui.panel.config.person.detail.allow_login_description"
                )}</span
              >
              <ha-switch
                slot="end"
                @change=${this._allowLoginChanged}
                ?disabled=${
                  this._user &&
                  (this._user.id === this.hass.user?.id ||
                    this._user.system_generated ||
                    this._user.is_owner)
                }
                .checked=${this._userId}
              ></ha-switch>
            </ha-row-item>

            ${this._renderUserFields()}
            ${
              this._deviceTrackersAvailable(this.hass)
                ? html`
                    <p>
                      ${this.hass.localize(
                        "ui.panel.config.person.detail.device_tracker_intro"
                      )}
                    </p>
                    <ha-entities-picker
                      .value=${this._deviceTrackers}
                      .includeDomains=${includeDomains}
                      .pickedEntityLabel=${this.hass.localize(
                        "ui.panel.config.person.detail.device_tracker_picked"
                      )}
                      .pickEntityLabel=${this.hass.localize(
                        "ui.panel.config.person.detail.device_tracker_pick"
                      )}
                      @value-changed=${this._deviceTrackersChanged}
                    >
                    </ha-entities-picker>
                  `
                : html`
                    <p>
                      ${this.hass!.localize(
                        "ui.panel.config.person.detail.no_device_tracker_available_intro"
                      )}
                    </p>
                    <ul>
                      <li>
                        <a
                          href=${documentationUrl(
                            this.hass,
                            "/integrations/#presence-detection"
                          )}
                          target="_blank"
                          rel="noreferrer"
                          >${this.hass!.localize(
                            "ui.panel.config.person.detail.link_presence_detection_integrations"
                          )}</a
                        >
                      </li>
                      <li>
                        <a
                          @click=${this.closeDialog}
                          href="/config/integrations"
                        >
                          ${this.hass!.localize(
                            "ui.panel.config.person.detail.link_integrations_page"
                          )}</a
                        >
                      </li>
                    </ul>
                  `
            }
          </div>
        </div>
        <ha-dialog-footer slot="footer">
          ${
            this._params.entry
              ? html`
                  <ha-button
                    slot="secondaryAction"
                    variant="danger"
                    appearance="plain"
                    @click=${this._deleteEntry}
                    .disabled=${
                      (this._user && this._user.is_owner) || this._submitting
                    }
                  >
                    ${this.hass!.localize("ui.panel.config.person.detail.delete")}
                  </ha-button>
                `
              : html`<ha-button
                  slot="secondaryAction"
                  appearance="plain"
                  @click=${this.closeDialog}
                >
                  ${this.hass!.localize("ui.common.cancel")}
                </ha-button>`
          }
          <ha-button
            slot="primaryAction"
            @click=${this._updateEntry}
            .disabled=${nameInvalid || this._submitting || !this.isDirtyState}
          >
            ${
              this._params.entry
                ? this.hass!.localize("ui.common.save")
                : this.hass!.localize("ui.common.add")
            }
          </ha-button>
        </ha-dialog-footer>
      </ha-dialog>
    `;
  }

  private _renderUserFields() {
    const user = this._user;
    if (!user) return nothing;
    return html`
      ${
        !user.system_generated
          ? html`
              <ha-row-item>
                <span slot="headline"
                  >${this.hass.localize(
                    "ui.panel.config.person.detail.username"
                  )}</span
                >
                <span slot="supporting-text">${user.username}</span>
                ${
                  this.hass.user?.is_owner
                    ? html`
                        <ha-icon-button
                          slot="end"
                          .path=${mdiPencil}
                          @click=${this._changeUsername}
                          .label=${this.hass.localize(
                            "ui.panel.config.person.detail.change_username"
                          )}
                        >
                        </ha-icon-button>
                      `
                    : nothing
                }
              </ha-row-item>
            `
          : nothing
      }
      ${
        !user.system_generated && this.hass.user?.is_owner
          ? html`
              <ha-row-item>
                <span slot="headline"
                  >${this.hass.localize(
                    "ui.panel.config.person.detail.password"
                  )}</span
                >
                <span slot="supporting-text">************</span>
                ${
                  this.hass.user?.is_owner
                    ? html`
                        <ha-icon-button
                          slot="end"
                          .path=${mdiPencil}
                          @click=${this._changePassword}
                          .label=${this.hass.localize(
                            "ui.panel.config.person.detail.change_password"
                          )}
                        >
                        </ha-icon-button>
                      `
                    : nothing
                }
              </ha-row-item>
            `
          : nothing
      }
      <ha-row-item>
        <span slot="headline"
          >${this.hass.localize(
            "ui.panel.config.person.detail.local_access_only"
          )}</span
        >
        <span slot="supporting-text"
          >${this.hass.localize(
            "ui.panel.config.person.detail.local_access_only_description"
          )}</span
        >
        <ha-switch
          slot="end"
          .disabled=${user.system_generated}
          .checked=${this._localOnly}
          @change=${this._localOnlyChanged}
        ></ha-switch>
      </ha-row-item>
      <ha-row-item>
        <span slot="headline"
          >${this.hass.localize("ui.panel.config.person.detail.admin")}</span
        >
        <span slot="supporting-text"
          >${this.hass.localize(
            "ui.panel.config.person.detail.admin_description"
          )}</span
        >
        <ha-switch
          slot="end"
          .disabled=${user.system_generated || user.is_owner}
          .checked=${this._isAdmin}
          @change=${this._adminChanged}
        ></ha-switch>
      </ha-row-item>
    `;
  }

  private _nameChanged(ev: InputEvent) {
    this._error = undefined;
    this._name = (ev.target as HTMLInputElement).value;
    this._updateDirtyState(this._currentState());
  }

  private _adminChanged(ev): void {
    this._isAdmin = ev.target.checked;
    this._updateDirtyState(this._currentState());
  }

  private _localOnlyChanged(ev): void {
    this._localOnly = ev.target.checked;
    this._updateDirtyState(this._currentState());
  }

  private async _allowLoginChanged(ev): Promise<void> {
    const target = ev.target;
    if (target.checked) {
      target.checked = false;
      showAddUserDialog(this, {
        userAddedCallback: async (user?: User) => {
          if (user) {
            target.checked = true;
            if (this._params!.entry && this._params!.updateEntry) {
              await this._params!.updateEntry({ user_id: user.id });
            }
            this._params?.refreshUsers?.();
            this._user = user;
            this._userId = user.id;
            this._isAdmin = user.group_ids.includes(SYSTEM_GROUP_ID_ADMIN);
            this._localOnly = user.local_only;
            this._updateDirtyState(this._currentState());
          }
        },
        name: this._name,
      });
    } else if (this._userId) {
      if (
        !(await showConfirmationDialog(this, {
          title: this.hass!.localize(
            "ui.panel.config.person.detail.confirm_delete_user_title"
          ),
          text: this.hass!.localize(
            "ui.panel.config.person.detail.confirm_delete_user_text",
            { name: this._name }
          ),
          confirmText: this.hass!.localize("ui.common.delete"),
          dismissText: this.hass!.localize("ui.common.cancel"),
          destructive: true,
        }))
      ) {
        target.checked = true;
        return;
      }
      await deleteUser(this.hass, this._userId);
      this._params?.refreshUsers?.();
      this._userId = undefined;
      this._user = undefined;
      this._isAdmin = undefined;
      this._localOnly = undefined;
      this._updateDirtyState(this._currentState());
    }
  }

  private _deviceTrackersChanged(ev: ValueChangedEvent<string[]>) {
    this._error = undefined;
    this._deviceTrackers = ev.detail.value;
    this._updateDirtyState(this._currentState());
  }

  private _pictureChanged(ev: ValueChangedEvent<string | null>) {
    this._error = undefined;
    this._picture = (ev.target as HaPictureUpload).value;
    this._updateDirtyState(this._currentState());
  }

  private async _changePassword() {
    if (!this._user) {
      return;
    }
    const credential = this._user.credentials.find(
      (cred) => cred.type === "homeassistant"
    );
    if (!credential) {
      showAlertDialog(this, {
        title: "No Home Assistant credentials found.",
      });
      return;
    }
    showAdminChangePasswordDialog(this, { userId: this._user.id });
  }

  private async _changeUsername() {
    if (!this._user) {
      return;
    }
    const credential = this._user.credentials.find(
      (cred) => cred.type === "homeassistant"
    );
    if (!credential) {
      showAlertDialog(this, {
        title: "No Home Assistant credentials found.",
      });
      return;
    }

    const newUsername = await showPromptDialog(this, {
      inputLabel: this.hass.localize(
        "ui.panel.config.users.change_username.new_username"
      ),
      confirmText: this.hass.localize(
        "ui.panel.config.users.change_username.change"
      ),
      title: this.hass.localize(
        "ui.panel.config.users.change_username.caption"
      ),
      defaultValue: this._user.username!,
    });
    if (newUsername) {
      try {
        await adminChangeUsername(this.hass, this._user.id, newUsername);
        this._params?.refreshUsers?.();
        this._user = { ...this._user, username: newUsername };
        showAlertDialog(this, {
          text: this.hass.localize(
            "ui.panel.config.users.change_username.username_changed"
          ),
        });
      } catch (err: any) {
        showAlertDialog(this, {
          title: this.hass.localize(
            "ui.panel.config.users.change_username.failed"
          ),
          text: err.message,
        });
      }
    }
  }

  private async _updateEntry() {
    this._submitting = true;
    try {
      if (
        (this._userId && this._name !== this._params!.entry?.name) ||
        this._isAdmin !==
          this._user?.group_ids.includes(SYSTEM_GROUP_ID_ADMIN) ||
        this._localOnly !== this._user?.local_only
      ) {
        await updateUser(this.hass!, this._userId!, {
          name: this._name.trim(),
          group_ids: [
            this._isAdmin ? SYSTEM_GROUP_ID_ADMIN : SYSTEM_GROUP_ID_USER,
          ],
          local_only: this._localOnly,
        });
        this._params?.refreshUsers?.();
      }
      const values: PersonMutableParams = {
        name: this._name.trim(),
        device_trackers: this._deviceTrackers,
        user_id: this._userId || null,
        picture: this._picture,
      };
      if (this._params!.entry) {
        await this._params!.updateEntry?.(values);
      } else {
        await this._params!.createEntry?.(values);
        this._personExists = true;
      }
      this._markDirtyStateClean();
      this.closeDialog();
    } catch (err: any) {
      this._error = err ? err.message : "Unknown error";
    } finally {
      this._submitting = false;
    }
  }

  private async _deleteEntry() {
    this._submitting = true;
    try {
      if (await this._params!.removeEntry?.()) {
        if (this._params!.entry!.user_id) {
          deleteUser(this.hass, this._params!.entry!.user_id);
        }
        this.closeDialog();
      }
    } finally {
      this._submitting = false;
    }
  }

  static get styles(): CSSResultGroup {
    return [
      haStyleDialog,
      css`
        ha-picture-upload {
          display: block;
        }
        ha-picture-upload {
          margin-bottom: 16px;
          --file-upload-image-border-radius: var(--ha-border-radius-circle);
        }
        ha-row-item {
          --ha-row-item-padding-inline: 0;
        }
        a {
          color: var(--primary-color);
        }
        p {
          color: var(--primary-text-color);
        }
      `,
    ];
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "dialog-person-detail": DialogPersonDetail;
  }
}
