import { useEffect, useRef, useState } from "react";
import type { PageProps } from "keycloakify/login/pages/PageProps";
import type { KcContext } from "../KcContext";
import type { I18n } from "../i18n";
import { Button } from "@/components/ui/button";

export default function QrLoginScan(props: PageProps<Extract<KcContext, { pageId: "qr-login-scan.ftl" }>, I18n>) {
    const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
    const { url, QRauthImage, QRauthExecId, QRauthToken, tabId, alignment, ShortCode, ShortCodeLink, refreshRate = 15 } = kcContext;

    const { msg, msgStr } = i18n;

    const formRef = useRef<HTMLFormElement>(null);
    const [showShortCode, setShowShortCode] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            formRef.current?.requestSubmit();
        }, refreshRate * 1000);

        return () => clearTimeout(timer);
    }, [refreshRate]);

    useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        if (params.get("qr_code_originated") === "true") {
            const el = document.getElementById("com-hadleyso-qr-auth");
            if (el) el.style.display = "none";
        }
    }, []);

    const qrContainerStyle: React.CSSProperties = {
        width: "45%",
        marginLeft: alignment === "Center" ? "auto" : alignment === "Right" ? "auto" : undefined,
        marginRight: alignment === "Center" || alignment === "Left" ? "auto" : undefined
    };

    return (
        <Template
            kcContext={kcContext}
            i18n={i18n}
            doUseDefaultCss={doUseDefaultCss}
            classes={classes}
            displayInfo={false}
            headerNode={msg("doQrCodeLogin")}
        >
            <div id="com-hadleyso-qr-auth" className={classes?.kcFormClass}>
                <div
                    id="com-hadleyso-qr-auth-js-target"
                    className="kcQrCodeContainer"
                    style={qrContainerStyle}
                    onClick={() => formRef.current?.requestSubmit()}
                >
                    <span className="kcQrTokenHidden">{QRauthToken}</span>
                    {QRauthImage ? (
                        <img
                            id="com-hadleyso-qr-auth-qr-code"
                            src={`data:image/png;base64,${QRauthImage}`}
                            alt={msgStr("ext-qr-code-login-display-name")}
                            className="kcQrCodeImage"
                        />
                    ) : (
                        <div className="kcQrCodePlaceholder">{msg("qrLoginLoading")}</div>
                    )}
                </div>

                {tabId && (
                    <p className="kcQrSessionClass">
                        <b>{msg("qrLoginSessionLabel")}</b> {tabId}
                    </p>
                )}

                {ShortCode && (
                    <p id="com-hadleyso-qr-auth-short-zone" className="kcQrShortCodeZone">
                        <Button
                            variant="link"
                            size="sm"
                            id="com-hadleyso-qr-auth-short-start"
                            onClick={event => {
                                setShowShortCode(true);
                                event.preventDefault();
                            }}
                        >
                            {msg("CannotScan")}
                        </Button>{" "}
                        |{" "}
                        <Button variant="link" size="sm" asChild>
                            <a href={ShortCodeLink}>{msg("UseShortCode")}</a>
                        </Button>
                    </p>
                )}

                {ShortCode && showShortCode && (
                    <p id="com-hadleyso-qr-auth-short-message" className="kcQrShortCodeMessage">
                        {msg("doShortCodeSteps")}
                        <br />
                        <br />
                        <b>{msg("doShortCode")}:</b> {ShortCode}
                    </p>
                )}

                <form
                    ref={formRef}
                    id={`com-hadleyso-qrcode-${QRauthExecId ?? "default"}`}
                    className={classes?.kcFormClass}
                    action={url.loginAction}
                    method="post"
                >
                    <input type="hidden" name="authenticationExecution" value={QRauthExecId ?? ""} />
                    <Button type="submit" size="lg">
                        {msgStr("doLogIn")}
                    </Button>
                </form>
            </div>
        </Template>
    );
}
