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

import { TemplateCenterCard } from "./card.js";

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

function TemplateCenterCards<TemplateType extends TemplateCenterAllowedTypes>({
    templates,
    showHidden,
    showDisabled = true,
    ...rest
}: {
    templates: TemplateType["afterPersist"][];
    showHidden?: boolean;
    showDisabled?: boolean;
} & Pick<
    ComponentProps<typeof TemplateCenterCard<TemplateType>>,
    "renderActions" | "renderTags" | "onSelect" | "onAcknowledgementClick" | "grayOutAlreadyExisting"
>) {
    const [initialLoaded, setInitialLoaded] = useState(false);

    useEffect(() => {
        if (!initialLoaded && templates.length > 0) {
            setInitialLoaded(true);
        }
    }, [initialLoaded, templates.length]);

    return templates.length > 0 || initialLoaded ? (
        <>
            {templates
                .filter(({ isHidden }) => (showHidden ? true : !isHidden))
                .filter(({ consumerData: { isDisabled } }) => (showDisabled ? true : !isDisabled))
                .map((template) => (
                    <TemplateCenterCard<TemplateType> template={template} key={template.identifier} {...rest} />
                ))}
        </>
    ) : (
        <Spin spinning style={{ marginTop: 10 }} />
    );
}

export { TemplateCenterCards };
