import { AKElement } from "#elements/Base";
import { LitFC } from "#elements/types";
import { ifPresent } from "#elements/utils/attributes";
import { isDefaultAvatar } from "#elements/utils/images";

import Styles from "#flow/FormStatic.css";
import { StageChallengeLike } from "#flow/types";

import { msg, str } from "@lit/localize";
import { CSSResult, html, nothing } from "lit";
import { customElement, property } from "lit/decorators.js";
import { guard } from "lit/directives/guard.js";

import PFAvatar from "@patternfly/patternfly/components/Avatar/avatar.css";

@customElement("ak-form-static")
export class AKFormStatic extends AKElement {
    static styles: CSSResult[] = [PFAvatar, Styles];

    public override role = "banner";
    public override ariaLabel = msg("User information");

    @property({ type: String })
    public avatar: string = "";

    @property({ type: String })
    public username: string = "";

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

        return html`<div class="primary-content">
                ${this.avatar && !isDefaultAvatar(this.avatar)
                    ? html`<img
                          class="pf-c-avatar"
                          src=${this.avatar}
                          alt=${this.username
                              ? msg(str`Avatar for ${this.username}`, {
                                    id: "avatar.alt-text-for-user",
                                })
                              : msg("User avatar", {
                                    id: "avatar.alt-text",
                                })}
                      />`
                    : nothing}
                <div class="username" aria-description=${msg("Username")}>${this.username}</div>
            </div>
            <div class="links">
                <slot name="link"></slot>
            </div>`;
    }
}

export interface FlowUserDetailsProps {
    challenge?: StageChallengeLike | null;
}

export const FlowUserDetails: LitFC<FlowUserDetailsProps> = ({ challenge }) => {
    const { pendingUserAvatar, pendingUser, flowInfo } = challenge || {};
    return guard(
        [pendingUserAvatar, pendingUser, flowInfo],
        () =>
            html`<ak-form-static
                .avatar=${ifPresent(pendingUserAvatar)}
                username=${ifPresent(pendingUser)}
            >
                ${flowInfo?.cancelUrl
                    ? html`
                          <div slot="link">
                              <a href=${flowInfo.cancelUrl}>${msg("Not you?")}</a>
                          </div>
                      `
                    : nothing}
            </ak-form-static>`,
    );
};

declare global {
    interface HTMLElementTagNameMap {
        "ak-form-static": AKFormStatic;
    }
}
