import { observer } from "mobx-react";
import { useCallback, useState } from "react";

import { TemplateCenter, useTemplateCenterProvider } from "@devowl-wp/react-cookie-banner-admin";
import type { ClientBlockerTemplate } from "@devowl-wp/service-cloud-consumer";

import { BlockerEditForm } from "./form.js";
import { useLocationQuery } from "../../../hooks/useLocationQuery.js";
import { useStores } from "../../../store/stores.js";
import { ConfigContent } from "../content.js";

import type { FC } from "react";

const BlockerTemplateCenter: FC = observer(() => {
    const {
        cookieStore,
        optionStore: { isTcf },
    } = useStores();
    const [fetched, setFetched] = useState(false);

    const [selectedTemplate, setSelectedTemplate] = useState<{
        identifier?: string;
        version?: number;
        overwriteAttributes?: any;
    }>();

    // Allow to force a template by query argument so the template center is disabled
    const {
        force,
        comingFromServiceCreation,
        attributes: queryAttributes,
        navigateAfterCreation = true,
    } = useLocationQuery();

    const fetchTemplates = useCallback(async () => {
        if (!fetched) {
            setFetched(true);
            await cookieStore.fetchTemplatesBlocker();
        }

        const result = Array.from(cookieStore.templatesBlocker.values()).map(({ data }) => data);
        result.sort((a, b) => a.headline.localeCompare(b.headline));
        return result;
    }, [fetched]);

    const [TemplateCenterContextProvider, templateCenterContextValue] = useTemplateCenterProvider(
        {
            type: "content-blocker",
            quickLinks: ["blocker-individual", "service-scanner", "cookie-experts"],
            enableLocalFilter: true,
            syncTemplates: () => {
                return cookieStore.fetchTemplatesBlocker({ storage: "redownload" });
            },
            fetchTemplates,
            fetchUse: async (identifier) => {
                // We do currently not have a "pagination", just load all
                await fetchTemplates();
                return cookieStore.templatesBlocker.get(identifier).fetchUse();
            },
            initialSelection: force,
            onSelect: (template, initialSelection) => {
                if (template?.tcfVendorIds.length > 0 && !isTcf) {
                    window.location.href = `#/settings/tcf?tcfIntegrationItem=${encodeURIComponent(
                        template.name,
                    )}&navigateAfterTcfActivation=${encodeURIComponent(`#/blocker/new?force=${template.identifier}`)}`;
                } else {
                    setSelectedTemplate({
                        identifier: template?.identifier,
                        version: template?.version,
                        overwriteAttributes:
                            initialSelection && queryAttributes ? JSON.parse(queryAttributes) : undefined,
                    });
                }
            },
        },
        {},
    );

    return selectedTemplate === undefined ? (
        <ConfigContent>
            <TemplateCenterContextProvider value={templateCenterContextValue}>
                <TemplateCenter<ClientBlockerTemplate> />
            </TemplateCenterContextProvider>
        </ConfigContent>
    ) : (
        <ConfigContent maxWidth="fixed">
            <BlockerEditForm
                comingFromServiceCreation={comingFromServiceCreation === "1"}
                template={
                    selectedTemplate.identifier
                        ? {
                              identifier: selectedTemplate.identifier,
                              version: selectedTemplate.version,
                          }
                        : undefined
                }
                overwriteAttributes={selectedTemplate.overwriteAttributes}
                navigateAfterCreation={navigateAfterCreation}
            />
        </ConfigContent>
    );
});

export { BlockerTemplateCenter };
