import { Spin } from "antd";
import { useCallback, useEffect, useState } from "react";

import { TemplateCenterFilter } from "./filter.js";
import { TemplateCenterHeader } from "./header.js";
import { useI18n } from "../../contexts/i18n.js";
import { useTemplateCenter } from "../../contexts/templateCenter.js";
import { useUpsell } from "../../contexts/upsell.js";
import { ASSETS_URL } from "../../hooks/useUpsellModal.js";
import { LearnMoreTag } from "../common/learnMoreTag.js";
import { UpsellModal } from "../upsell/modal.js";

import type { TemplateCenterAllowedTypes } from "../../contexts/templateCenter.js";

function TemplateCenter<TemplateType extends TemplateCenterAllowedTypes>() {
    const { __ } = useI18n();
    const [busy, setBusy] = useState(false);
    const { type, fetchUse, initialSelection, onSelect } = useTemplateCenter();
    const { isPro, isLicensed } = useUpsell();
    const [noLicenseInContainerRef, setNoLicenseInContainerRef] = useState<HTMLDivElement>();
    const [templates, setTemplates] = useState<TemplateType["afterPersist"][]>([]);

    // Initial selection, e.g. by React Router parameter
    useEffect(() => {
        if (initialSelection) {
            (async () => {
                if (initialSelection === "scratch") {
                    onSelect(undefined, true);
                } else {
                    setBusy(true);
                    try {
                        const use = await fetchUse(initialSelection);
                        onSelect(use as any, true);
                    } finally {
                        setBusy(false);
                    }
                }
            })();
        }
    }, [initialSelection]);

    const handleSelect = useCallback(
        async (template: TemplateType["afterPersist"]) => {
            if (template) {
                setBusy(true);
                try {
                    const use = await fetchUse(template.identifier, template as any);
                    onSelect(use as any);
                } finally {
                    setBusy(false);
                }
            } else {
                onSelect(undefined);
            }
        },
        [onSelect],
    );

    if (initialSelection) {
        return (
            <div style={{ textAlign: "center" }}>
                <Spin spinning />
            </div>
        );
    }

    return (
        <Spin spinning={busy}>
            <div style={{ textAlign: "center" }}>
                <TemplateCenterHeader onSelect={handleSelect} />
                <h2 style={{ margin: "20px 0", fontWeight: 400, fontSize: "23px" }}>
                    {__("...or create it from one of our templates")}
                </h2>
                <TemplateCenterFilter<TemplateType>
                    onFetched={setTemplates}
                    cards={{
                        templates,
                        onSelect: handleSelect,
                    }}
                >
                    {type === "service" && (
                        <>
                            <LearnMoreTag
                                url={__("https://devowl.io/knowledge-base/real-cookie-banner-find-all-services/")}
                                label={__("How do I find all services (cookies) on my website?")}
                                style={{ marginBottom: 10 }}
                            />
                            <br />
                        </>
                    )}
                </TemplateCenterFilter>
                {!isLicensed && (
                    <>
                        <UpsellModal
                            title={
                                type === "service"
                                    ? __("Service templates with technical and legal details from the Service Cloud")
                                    : __("Content Blocker with suitable settings from the Service Cloud")
                            }
                            inContainer
                            inContainerElement={noLicenseInContainerRef}
                            mode="license-activation"
                            feature="templates"
                            description={
                                (type === "service"
                                    ? __(
                                          "Templates for hundreds of services that you could be running on your website will save you a lot of time and work when setting up your cookie banner. The current service templates database must be downloaded from Real Cookie Banner's Service Cloud. The data will be downloaded locally to your server, so your website visitors will not need to connect to the cloud.",
                                      )
                                    : __(
                                          "Templates to block for hundreds of services you might use on your website will save you a lot of time and work when setting up your cookie banner. The current service templates database must be downloaded from Real Cookie Banner's Service Cloud. The data will be downloaded locally to your server, so your website visitors will not need to connect to the cloud.",
                                      )) +
                                (isPro
                                    ? ""
                                    : ` ${__(
                                          "We also offer you a lot of templates in the free version, you can activate your free licence at any time, without any costs.",
                                      )}`)
                            }
                            assetName="service-cloud.svg"
                            assetMaxHeight={200}
                        />
                        <div
                            ref={setNoLicenseInContainerRef}
                            className="rcb-antd-modal-mount"
                            style={{
                                height: 1400,
                                backgroundImage: `url('${ASSETS_URL}templates-blured.jpg')`,
                                backgroundSize: "contain",
                                backgroundRepeat: "no-repeat",
                                backgroundPosition: "center top",
                            }}
                        />
                    </>
                )}
            </div>
        </Spin>
    );
}

export { TemplateCenter };
