import { SafeDictionary } from "@insite/client-framework/Common/Types";
import {
    DoNotFollowLinks,
    ExcludeFromNavigation,
    ExcludeFromSignInRequired,
    HideFromSearchEngines,
    HideFromSiteSearch,
    MetaDescription,
    MetaKeywords,
} from "@insite/client-framework/Types/FieldDefinition";
import PageModule from "@insite/client-framework/Types/PageModule";
import PageProps from "@insite/client-framework/Types/PageProps";
import Page from "@insite/mobius/Page";
// eslint-disable-next-line spire/fenced-imports
import { areLabelsLoaded, setLabels, TS } from "@insite/shell/TS";
import * as React from "react";
import { useEffect, useState } from "react";
import styled from "styled-components";
import { fetch } from "@insite/client-framework/ServerSideRendering";

const VariantRootPage = ({ id }: PageProps) => {
    const [labelsLoaded, setLabelsLoaded] = useState(areLabelsLoaded());
    const [label, setLabel] = useState("");

    useEffect(() => {
        const loadLabelsIfNeeded = async () => {
            if (labelsLoaded) {
                setLabel(TS("This page has multiple variants."));
                return;
            }

            const res = await fetch(`/admin/translations`);
            const data = await res.json();

            const labelsByKey: SafeDictionary<string> = {};
            for (const label of data.labels) {
                labelsByKey[label.label] = label.localizedLabel;
            }
            setLabels(labelsByKey, data.isDebugModeEnabled, data.languageCode);
            setLabelsLoaded(true);
        };

        loadLabelsIfNeeded();
    }, [labelsLoaded]);

    return (
        <Page key={id}>
            <MessageWrapper>{label}</MessageWrapper>
        </Page>
    );
};

const pageModule: PageModule = {
    component: VariantRootPage,
    definition: {
        displayName: "Shared Fields",
        hasEditableUrlSegment: false,
        hasEditableTitle: false,
        pageType: "System",
        fieldDefinitions: [
            MetaKeywords,
            MetaDescription,
            HideFromSearchEngines,
            DoNotFollowLinks,
            HideFromSiteSearch,
            ExcludeFromNavigation,
            ExcludeFromSignInRequired,
        ],
    },
};

const MessageWrapper = styled.div`
    margin-top: 300px;
    text-align: center;
    color: #999;
    font-weight: bold;
    font-size: 22px;
`;

export default pageModule;
