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

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

import { CookieEditForm } 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 CookieTemplateCenter: FC = observer(() => {
    const { cookieStore } = 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, attributes: queryAttributes, navigateAfterCreation = true } = useLocationQuery();

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

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

    const [TemplateCenterContextProvider, templateCenterContextValue] = useTemplateCenterProvider({
        type: "service",
        quickLinks: ["service-individual", "service-scanner", "cookie-experts"],
        enableLocalFilter: true,
        syncTemplates: () => {
            return cookieStore.fetchTemplatesServices({ storage: "redownload" });
        },
        fetchTemplates,
        fetchUse: async (identifier) => {
            // We do currently not have a "pagination", just load all
            await fetchTemplates();
            return cookieStore.templatesServices.get(identifier).fetchUse();
        },
        initialSelection: force,
        onSelect: (template, initialSelection) =>
            setSelectedTemplate({
                identifier: template?.identifier,
                version: template?.version,
                overwriteAttributes: initialSelection && queryAttributes ? JSON.parse(queryAttributes) : undefined,
            }),
    });

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

export { CookieTemplateCenter };
