/**
 * @mergeTarget
 * @module Src/Screens/Login
 */

import {
  LisioParameterNames,
  LisioProfileNames,
} from "@lisio/lisio-profils";
import { LisioComponent, LisioComponentStyles } from "@lisio/lisio-engine";
import { getInputManager, getMessageManager } from "../../../managers/manager-registry";
import { ElementsContainer } from "../../components/containers/elements-container/elements-container";
import { CustomButton } from "../../components/custom-button/custom-button";
import { CustomImage } from "../../components/custom-image/custom-image";
import { CustomLink } from "../../components/custom-link/custom-link";
import { CustomText } from "../../components/custom-text/custom-text";
import { AuthInput } from "../../components/inputs/auth/auth-input";
import { LisioScreen } from "../lisio-screen";
import { loginScreenStyles } from "./login-screen.css";
import {
  BooleanParameterRenderObject,
  CategoryRenderObject,
  MergedCategoriesNames,
  NumberParameterRenderObject,
  ProfileRenderObject,
  ScreenNames,
  StringParameterRenderObject,
  VisualCategoryNames,
} from "../screen-types";

class LoginScreen extends LisioScreen {
  protected _categoryRenderObjects: Map<
    MergedCategoriesNames,
    CategoryRenderObject
  > = new Map();

  protected _profileRenderObjects: Map<LisioProfileNames, ProfileRenderObject> =
    new Map();

  protected _parameterRenderObjects: Map<
    LisioParameterNames,
    | BooleanParameterRenderObject
    | StringParameterRenderObject
    | NumberParameterRenderObject
  > = new Map();

  /**
   * Private attribute to store email input
   * @source
   */
  private _emailInput: AuthInput;

  /**
   * Private attribute to store password input
   * @source
   */
  private _passwordInput: AuthInput;

  /**
   * Private attribute to store error text
   * @source
   */
  private _errorText: CustomText;

  /**
   * Private attribute to store password toggle image
   * @source
   */
  private _passwordToggleImage: CustomImage;

  /**
   * Private attribute to store password toggle button
   * @source
   */
  private _passwordToggleButton: CustomButton;

  /**
   * Private attribute to store password visibility state
   * @source
   */
  private _isPswShown = false;

  /**
   * Private attribute to store social auth container
   * @source
   */
  private _socialAuthContainer: ElementsContainer;

  public async render(): Promise<string> {
    getInputManager().disableAll(true);
    getMessageManager().sendDisableAllMessage();
    return `
      <section id="${this._id}">
        <children></children>
      </section>
    `;
  }

  public postRender(): void {
    this._emailInput.focus();
  }

  public showErrorMessage(text: string) {
    this._errorText.changeText(text, true);
    if (text === "") {
      this._errorText.showHideElement(false);
    } else {
      this._errorText.showHideElement(true);
    }
  }

  /**
   * Private method to clear error message
   * @returns Returns nothing
   * @source
   */
  private clearErrorMessage(): void {
    this.showErrorMessage("");
  }

  /**
   * Private method to submit auth form
   * @returns Returns nothing
   * @source
   */
  private submit(): void {
    this.clearErrorMessage();
    getMessageManager().sendAuthInformations(
      this._emailInput.value,
      this._passwordInput.value,
    );
  }

  /**
   * Private method to handle enter key in auth inputs
   * @param {KeyboardEvent} event - Keyboard event
   * @returns Returns nothing
   * @source
   */
  private handleEnterKey(event: KeyboardEvent): void {
    if (event.key === "Enter") {
      this.submit();
    }
  }

  /**
   * Private method to toggle password visibility
   * @returns Returns nothing
   * @source
   */
  private togglePasswordVisibility(): void {
    this._isPswShown = !this._isPswShown;
    this._passwordInput.changeType(this._isPswShown ? "text" : "password");
    this._passwordToggleImage.changeSrc(
      this._isPswShown ? "./assets/imgs/hide.svg" : "./assets/imgs/show.svg",
    );
    this._passwordToggleImage.changeAlt(
      this._isPswShown
        ? "Masquer le mot de passe"
        : "Afficher le mot de passe",
      true,
    );
    this._passwordToggleButton.changeAriaLabel(
      this._isPswShown
        ? "Masquer le mot de passe"
        : "Afficher le mot de passe",
      true,
    );
  }

  /**
   * Private method to create an input field container
   * @param {string} label - Field label
   * @param {string} inputId - Input id referenced by label
   * @param {AuthInput} input - Input component
   * @param {CustomButton | undefined} trailingButton - Optional trailing button
   * @returns Returns input field container
   * @source
   */
  private createInputField(
    label: string,
    inputId: string,
    input: AuthInput,
    trailingButton?: CustomButton,
  ): ElementsContainer {
    const children: LisioComponent[] = [
      new CustomText(
        "label",
        label,
        true,
        ["login-input-label", "bold"],
        inputId,
      ),
      input,
    ];
    if (trailingButton != undefined) {
      children.push(trailingButton);
    }
    return new ElementsContainer(children, undefined, ["login-input-container"]);
  }

  /**
   * Private method to create the reset password link
   * @returns Returns reset password link
   * @source
   */
  private createResetPasswordLink(): CustomLink {
    return new CustomLink(
      `${import.meta.env.VITE_RESET_PASSWORD_DOMAIN}/fr/forgot-password`,
      [
        new CustomText("span", "Mot de passe oublié ?", true, [
          "login-reset-password-text",
        ]),
      ],
      undefined,
      true,
      ["login-reset-password-link"],
    );
  }

  /**
   * Private method to create a social auth button
   * @param {string} id - Button id
   * @param {string} label - Button label
   * @param {"google" | "microsoft"} ssoType - Social auth type
   * @returns Returns social auth button
   * @source
   */
  private createSocialAuthButton(
    id: string,
    label: string,
    ssoType: "google" | "microsoft",
  ): CustomButton {
    const logoPath =
      ssoType === "google"
        ? "./assets/imgs/logo_google.webp"
        : "./assets/imgs/logo_microsoft.webp";

    return new CustomButton(
      id,
      [
        new CustomImage(
          logoPath,
          { id: "", noTranslate: true },
          ["login-social-button-logo"],
        ),
        new CustomText("span", label, true, [
          "login-social-button-text",
          "bold",
        ]),
      ],
      () => {
        this.clearErrorMessage();
        getMessageManager().sendSSOAuth(ssoType);
      },
      ["login-social-button", "btn-pill", "width-100"],
      {
        label: {
          id: label,
          noTranslate: true,
        },
      },
    );
  }

  /**
   * Constructor of class {@link LoginScreen | LoginScreen}
   * @source
   */
  constructor() {
    ScreenNames[LoginScreen.name] = "login-screen";
    super(
      LoginScreen.name,
      LoginScreen.name,
      VisualCategoryNames.LOGIN,
    );

    this._emailInput = new AuthInput(
      "login-email-input",
      "email",
      "email",
      "Entrez ici votre email",
      "email",
      ["login-field-input"],
      new Map<string, string>([["aria-label", "Email"]]),
      [
        {
          triggerer: "keydown",
          handler: (event: KeyboardEvent) => {
            this.handleEnterKey(event);
          },
        },
        {
          triggerer: "input",
          handler: () => {
            this.clearErrorMessage();
          },
        },
      ],
    );
    this._passwordInput = new AuthInput(
      "login-password-input",
      "password",
      "password",
      "Entrez ici votre mot de passe",
      "current-password",
      ["login-field-input", "login-field-input-password"],
      new Map<string, string>([["aria-label", "Mot de passe"]]),
      [
        {
          triggerer: "keydown",
          handler: (event: KeyboardEvent) => {
            this.handleEnterKey(event);
          },
        },
        {
          triggerer: "input",
          handler: () => {
            this.clearErrorMessage();
          },
        },
      ],
    );
    this._passwordToggleImage = new CustomImage(
      "./assets/imgs/show.svg",
      { noTranslate: true, id: "Afficher le mot de passe" },
      ["login-password-toggle-image"],
    );
    this._passwordToggleButton = new CustomButton(
      "login-password-toggle-button",
      [this._passwordToggleImage],
      () => {
        this.togglePasswordVisibility();
      },
      ["login-password-toggle"],
      {
        label: {
          id: "Afficher le mot de passe",
          noTranslate: true,
        },
      },
    );
    this._errorText = new CustomText(
      "p",
      " ",
      true,
      ["error-text", "hidden"],
      undefined,
      "login-error-text",
    );
    this._errorText.changeText("", true);
    this._socialAuthContainer = new ElementsContainer(
      [
        new ElementsContainer(
          [
            this.createSocialAuthButton(
              "login-google-button",
              "Se connecter avec Google",
              "google",
            ),
            this.createSocialAuthButton(
              "login-microsoft-button",
              "Se connecter avec Microsoft",
              "microsoft",
            ),
          ],
          undefined,
          ["login-social-buttons"],
        ),
      ],
      undefined,
      ["login-social-auth"],
    );

    this._children.push(
      new ElementsContainer(
        [
          new ElementsContainer(
            [
              new CustomText("h1", "Connexion", true, [
                "login-title",
                "bold",
              ]),
            ],
            undefined,
            ["login-copy"],
          ),
          new ElementsContainer(
            [
              this._socialAuthContainer,
              new CustomText(
                "p",
                "Ou",
                true,
                ["login-divider-title", "regular", "text-center"],
              ),
              this.createInputField(
                "Email",
                "login-email-input",
                this._emailInput,
              ),
              this.createInputField(
                "Mot de passe",
                "login-password-input",
                this._passwordInput,
                this._passwordToggleButton,
              ),
              this.createResetPasswordLink(),
              this._errorText,
              new CustomButton(
                "login-submit-button",
                [
                  new CustomText(
                    "span",
                    "Me connecter",
                    true,
                    ["white", "bold"],
                  ),
                ],
                () => {
                  this.submit();
                },
                ["login-submit-button", "btn-pill", "green"],
                {
                  label: {
                    id: "Me connecter",
                    noTranslate: true,
                  },
                },
              ),
            ],
            undefined,
            ["login-form"],
          ),
        ],
        undefined,
        ["login-screen-content"],
      ),
    );

    new LisioComponentStyles(ScreenNames[LoginScreen.name], loginScreenStyles);
  }
}


export { LoginScreen };
