import "#admin/providers/RelatedApplicationButton";
import "#admin/events/ObjectChangelog";
import "#admin/rbac/ak-rbac-object-permission-page";
import "#admin/rbac/ObjectPermissionModal";
import "#elements/CodeMirror";
import "#elements/EmptyState";
import "#elements/Tabs";
import "#elements/tasks/TaskList";
import "#elements/ak-mdx/index";
import "#elements/buttons/ModalButton";
import "#elements/buttons/SpinnerButton/index";

import { DEFAULT_CONFIG } from "#common/api/config";
import { EVENT_REFRESH } from "#common/constants";

import { AKElement } from "#elements/Base";
import { modalInvoker } from "#elements/dialogs";
import { SlottedTemplateResult } from "#elements/types";

import renderDescriptionList from "#components/DescriptionList";

import { OAuth2ProviderFormPage } from "#admin/providers/oauth2/OAuth2ProviderForm";

import {
    ClientTypeEnum,
    CoreApi,
    CoreUsersListRequest,
    ModelEnum,
    OAuth2Provider,
    OAuth2ProviderLogoutMethodEnum,
    OAuth2ProviderSetupURLs,
    PropertyMappingPreview,
    ProvidersApi,
    User,
} from "@goauthentik/api";
import { IDGenerator } from "@goauthentik/core/id";

import MDProviderOAuth2 from "~docs/add-secure-apps/providers/oauth2/index.mdx";

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

import PFBanner from "@patternfly/patternfly/components/Banner/banner.css";
import PFButton from "@patternfly/patternfly/components/Button/button.css";
import PFCard from "@patternfly/patternfly/components/Card/card.css";
import PFContent from "@patternfly/patternfly/components/Content/content.css";
import PFDescriptionList from "@patternfly/patternfly/components/DescriptionList/description-list.css";
import PFDivider from "@patternfly/patternfly/components/Divider/divider.css";
import PFForm from "@patternfly/patternfly/components/Form/form.css";
import PFFormControl from "@patternfly/patternfly/components/FormControl/form-control.css";
import PFPage from "@patternfly/patternfly/components/Page/page.css";
import PFGrid from "@patternfly/patternfly/layouts/Grid/grid.css";

export function TypeToLabel(type?: ClientTypeEnum): string {
    if (!type) return "";
    switch (type) {
        case ClientTypeEnum.Confidential:
            return msg("Confidential");
        case ClientTypeEnum.Public:
            return msg("Public");
        case ClientTypeEnum.UnknownDefaultOpenApi:
            return msg("Unknown type");
    }
}

export function LogoutMethodToLabel(method?: OAuth2ProviderLogoutMethodEnum): string {
    if (!method) return "";
    switch (method) {
        case OAuth2ProviderLogoutMethodEnum.Backchannel:
            return msg("Back-channel");
        case OAuth2ProviderLogoutMethodEnum.Frontchannel:
            return msg("Front-channel");
        case OAuth2ProviderLogoutMethodEnum.UnknownDefaultOpenApi:
            return msg("Unknown");
    }
}

@customElement("ak-provider-oauth2-view")
export class OAuth2ProviderViewPage extends AKElement {
    @property({ type: Number })
    set providerID(value: number) {
        new ProvidersApi(DEFAULT_CONFIG)
            .providersOauth2Retrieve({
                id: value,
            })
            .then((prov) => {
                this.provider = prov;
            });
    }

    @property({ attribute: false })
    provider?: OAuth2Provider;

    @state()
    providerUrls?: OAuth2ProviderSetupURLs;

    @state()
    preview?: PropertyMappingPreview;

    @state()
    previewUser?: User;

    static styles: CSSResult[] = [
        PFButton,
        PFPage,
        PFGrid,
        PFContent,
        PFCard,
        PFDescriptionList,
        PFForm,
        PFFormControl,
        PFBanner,
        PFDivider,
    ];

    constructor() {
        super();
        this.addEventListener(EVENT_REFRESH, () => {
            if (!this.provider?.pk) return;
            this.providerID = this.provider?.pk;
        });
    }

    fetchPreview(): void {
        new ProvidersApi(DEFAULT_CONFIG)
            .providersOauth2PreviewUserRetrieve({
                id: this.provider?.pk || 0,
                forUser: this.previewUser?.pk,
            })
            .then((preview) => (this.preview = preview));
    }

    render(): SlottedTemplateResult {
        if (!this.provider) {
            return nothing;
        }
        return html`<main part="main">
            <ak-tabs part="tabs">
                <div
                    role="tabpanel"
                    tabindex="0"
                    slot="page-overview"
                    id="page-overview"
                    aria-label="${msg("Overview")}"
                    @activate=${() => {
                        new ProvidersApi(DEFAULT_CONFIG)
                            .providersOauth2SetupUrlsRetrieve({
                                id: this.provider?.pk || 0,
                            })
                            .then((prov) => {
                                this.providerUrls = prov;
                            });
                    }}
                >
                    ${this.renderTabOverview()}
                </div>
                <div
                    role="tabpanel"
                    tabindex="0"
                    slot="page-preview"
                    id="page-preview"
                    aria-label="${msg("Preview")}"
                    @activate=${() => {
                        this.fetchPreview();
                    }}
                >
                    ${this.renderTabPreview()}
                </div>
                <div
                    role="tabpanel"
                    tabindex="0"
                    slot="page-changelog"
                    id="page-changelog"
                    aria-label="${msg("Changelog")}"
                    class="pf-c-page__main-section pf-m-no-padding-mobile"
                >
                    <div class="pf-c-card">
                        <ak-object-changelog
                            targetModelPk=${this.provider?.pk || ""}
                            targetModelName=${this.provider?.metaModelName || ""}
                        >
                        </ak-object-changelog>
                    </div>
                </div>
                <ak-rbac-object-permission-page
                    role="tabpanel"
                    tabindex="0"
                    slot="page-permissions"
                    id="page-permissions"
                    aria-label="${msg("Permissions")}"
                    model=${ModelEnum.AuthentikProvidersOauth2Oauth2provider}
                    objectPk=${this.provider.pk}
                ></ak-rbac-object-permission-page>
            </ak-tabs>
        </main>`;
    }

    renderTabOverview(): SlottedTemplateResult {
        const [appLabel, modelName] = ModelEnum.AuthentikProvidersOauth2Oauth2provider.split(".");
        return html`${this.provider?.assignedApplicationName
                ? nothing
                : html`<div slot="header" class="pf-c-banner pf-m-warning">
                      ${msg("Warning: Provider is not used by an Application.")}
                  </div>`}
            <div class="pf-c-page__main-section pf-m-no-padding-mobile pf-l-grid pf-m-gutter">
                <div
                    class="pf-c-card pf-l-grid__item pf-m-12-col pf-m-4-col-on-xl pf-m-4-col-on-2xl"
                >
                    <div class="pf-c-card__title">${msg("Info")}</div>
                    <div class="pf-c-card__body">
                        ${renderDescriptionList([
                            [msg("Name"), html`${this.provider?.name}`],
                            [
                                msg("Assigned to application"),
                                html`<ak-provider-related-application .provider=${this.provider}>
                                </ak-provider-related-application>`,
                            ],
                            [msg("Client Type"), html`${TypeToLabel(this.provider?.clientType)}`],
                            [msg("Client ID"), html`${this.provider?.clientId}`],
                            [
                                msg("Redirect URIs"),
                                (this.provider?.redirectUris || []).length > 0
                                    ? html`<ul>
                                          ${this.provider?.redirectUris.map((ru) => {
                                              return html`<li class="pf-m-monospace">
                                                  ${ru.matchingMode}: ${ru.url}
                                              </li>`;
                                          })}
                                      </ul>`
                                    : "-",
                            ],
                            [
                                msg("Logout URI"),
                                this.provider?.logoutUri !== "" ? this.provider?.logoutUri : "-",
                            ],
                            [
                                msg("Logout Method"),
                                html`${LogoutMethodToLabel(this.provider?.logoutMethod)}`,
                            ],
                            [
                                msg("Related actions"),
                                html`<button
                                    class="pf-c-button pf-m-primary pf-m-block"
                                    ${modalInvoker(OAuth2ProviderFormPage, {
                                        instancePk: this.provider?.pk || 0,
                                    })}
                                >
                                    ${msg("Edit")}
                                </button>`,
                            ],
                        ])}
                    </div>
                </div>
                <div class="pf-c-card pf-l-grid__item pf-m-8-col">
                    <div class="pf-c-card__body">
                        <form class="pf-c-form">
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("providerInfo")}"
                                >
                                    <span class="pf-c-form__label-text"
                                        >${msg("OpenID Configuration URL")}</span
                                    >
                                </label>
                                <input
                                    id="${IDGenerator.elementID("providerInfo")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.providerInfo || msg("-")}"
                                />
                            </div>
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("issuer")}"
                                >
                                    <span class="pf-c-form__label-text"
                                        >${msg("OpenID Configuration Issuer")}</span
                                    >
                                </label>
                                <input
                                    id="${IDGenerator.elementID("issuer")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.issuer || msg("-")}"
                                />
                            </div>
                        </form>
                    </div>
                    <hr class="pf-c-divider" />
                    <div class="pf-c-card__body">
                        <form class="pf-c-form">
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("authorize")}"
                                >
                                    <span class="pf-c-form__label-text"
                                        >${msg("Authorize URL")}</span
                                    >
                                </label>
                                <input
                                    id="${IDGenerator.elementID("authorize")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.authorize || msg("-")}"
                                />
                            </div>
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("token")}"
                                >
                                    <span class="pf-c-form__label-text">${msg("Token URL")}</span>
                                </label>
                                <input
                                    id="${IDGenerator.elementID("token")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.token || msg("-")}"
                                />
                            </div>
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("userInfo")}"
                                >
                                    <span class="pf-c-form__label-text"
                                        >${msg("Userinfo URL")}</span
                                    >
                                </label>
                                <input
                                    id="${IDGenerator.elementID("userInfo")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.userInfo || msg("-")}"
                                />
                            </div>
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("logout")}"
                                >
                                    <span class="pf-c-form__label-text">${msg("Logout URL")}</span>
                                </label>
                                <input
                                    id="${IDGenerator.elementID("logout")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.logout || msg("-")}"
                                />
                            </div>
                            <div class="pf-c-form__group">
                                <label
                                    class="pf-c-form__label"
                                    for="${IDGenerator.elementID("jwks")}"
                                >
                                    <span class="pf-c-form__label-text">${msg("JWKS URL")}</span>
                                </label>
                                <input
                                    id="${IDGenerator.elementID("jwks")}"
                                    class="pf-c-form-control"
                                    readonly
                                    type="text"
                                    value="${this.providerUrls?.jwks || msg("-")}"
                                />
                            </div>
                        </form>
                    </div>
                </div>
                <div
                    class="pf-c-card pf-l-grid__item pf-m-12-col pf-m-12-col-on-xl pf-m-12-col-on-2xl"
                >
                    <div class="pf-c-card pf-l-grid__item pf-m-12-col-on-2xl">
                        <div class="pf-c-card__title">${msg("Tasks")}</div>
                        <ak-task-list
                            .relObjAppLabel=${appLabel}
                            .relObjModel=${modelName}
                            .relObjId="${this.provider?.pk}"
                        ></ak-task-list>
                    </div>
                </div>
                <div
                    class="pf-c-card pf-l-grid__item pf-m-12-col pf-m-12-col-on-xl pf-m-12-col-on-2xl"
                >
                    <div class="pf-c-card__body">
                        <ak-mdx
                            .url=${MDProviderOAuth2}
                            .replacers=${[
                                (input: string) => {
                                    if (!this.provider) {
                                        return input;
                                    }
                                    return input.replaceAll(
                                        "<application slug>",
                                        this.provider.assignedApplicationSlug ??
                                            "<application slug>",
                                    );
                                },
                            ]}
                        ></ak-mdx>
                    </div>
                </div>
            </div>`;
    }

    renderTabPreview(): SlottedTemplateResult {
        if (!this.provider) {
            return nothing;
        }
        return html` <div
            class="pf-c-page__main-section pf-m-no-padding-mobile pf-l-grid pf-m-gutter"
        >
            <div class="pf-c-card">
                <div class="pf-c-card__title">${msg("JWT payload")}</div>
                <div class="pf-c-card__body">
                    ${renderDescriptionList(
                        [
                            [
                                html`<label for="${IDGenerator.elementID("preview-user")}"
                                    >${msg("Preview for user")}</label
                                >`,
                                html`
                                    <ak-search-select
                                        id="${IDGenerator.elementID("preview-user")}"
                                        .fetchObjects=${async (query?: string): Promise<User[]> => {
                                            const args: CoreUsersListRequest = {
                                                ordering: "username",
                                            };
                                            if (query !== undefined) {
                                                args.search = query;
                                            }
                                            const users = await new CoreApi(
                                                DEFAULT_CONFIG,
                                            ).coreUsersList(args);
                                            return users.results;
                                        }}
                                        .renderElement=${(user: User): string => {
                                            return user.username;
                                        }}
                                        .renderDescription=${(user: User): TemplateResult => {
                                            return html`${user.name}`;
                                        }}
                                        .value=${(user: User | undefined): number | undefined => {
                                            return user?.pk;
                                        }}
                                        .selected=${(user: User): boolean => {
                                            return user.pk === this.previewUser?.pk;
                                        }}
                                        blankable
                                        @ak-change=${(ev: CustomEvent) => {
                                            this.previewUser = ev.detail.value;
                                            this.fetchPreview();
                                        }}
                                    >
                                    </ak-search-select>
                                `,
                            ],
                        ],
                        { horizontal: true },
                    )}
                </div>
                <div class="pf-c-card__body">
                    ${this.preview
                        ? html`<pre>${JSON.stringify(this.preview?.preview, null, 4)}</pre>`
                        : html` <ak-empty-state loading></ak-empty-state> `}
                </div>
            </div>
        </div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        "ak-provider-oauth2-view": OAuth2ProviderViewPage;
    }
}
