import { useEffect, useState } from "react";
import { Typography, Spin, Flex } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import type { PageProps } from "keycloakify/login/pages/PageProps";
import type { KcContext } from "../KcContext";
import type { I18n } from "../i18n";

const { Text } = Typography;

export default function SamlPostForm(props: PageProps<Extract<KcContext, { pageId: "saml-post-form.ftl" }>, I18n>) {
    const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
    const { msgStr, msg } = i18n;
    const { samlPost } = kcContext;
    const [htmlFormElement, setHtmlFormElement] = useState<HTMLFormElement | null>(null);

    // Custom spinner icon
    const antIcon = <LoadingOutlined style={{ fontSize: 24, color: "#000000" }} spin />;

    // Handle form submission
    useEffect(() => {
        if (htmlFormElement === null) {
            return;
        }

        // Storybook
        if (samlPost.url === "#") {
            alert("In a real Keycloak the user would be redirected immediately");
            return;
        }

        // Submit the form after a brief delay to show the loading animation
        const timeoutId = setTimeout(() => {
            htmlFormElement.submit();
        }, 1500);

        return () => clearTimeout(timeoutId);
    }, [htmlFormElement, samlPost.url]);

    return (
        <Template kcContext={kcContext} i18n={i18n} doUseDefaultCss={doUseDefaultCss} classes={classes} headerNode={msg("saml.post-form.title")}>
            <Flex align="middle" justify="start" gap={"middle"}  style={{ padding: '0 15px'}}>
                <Spin indicator={antIcon} />

                <Text style={{ margin: 0 }}>{msg("saml.post-form.message")}</Text>
            </Flex>

            <form name="saml-post-binding" method="post" action={samlPost.url} ref={setHtmlFormElement} style={{ display: "none" }}>
                {samlPost.SAMLRequest && <input type="hidden" name="SAMLRequest" value={samlPost.SAMLRequest} />}
                {samlPost.SAMLResponse && <input type="hidden" name="SAMLResponse" value={samlPost.SAMLResponse} />}
                {samlPost.relayState && <input type="hidden" name="RelayState" value={samlPost.relayState} />}
                <noscript>
                    <Text>{msg("saml.post-form.js-disabled")}</Text>
                    <input type="submit" value={msgStr("doContinue")} />
                </noscript>
            </form>
        </Template>
    );
}
