import { App, Badge, Card, Collapse, Divider, Tag, Tooltip } from "antd";

import { ERcbTier } from "@devowl-wp/api-real-cookie-banner";
import type { CdnMiddlewareConsumerData, ClientServiceTemplate } from "@devowl-wp/service-cloud-consumer";

import { useI18n } from "../../contexts/i18n.js";
import { useUpsell } from "../../contexts/upsell.js";
import { UPSELL_TAG_BACKGROUND_COLOR, useUpsellModal } from "../../hooks/useUpsellModal.js";

import type { TemplateCenterAllowedTypes } from "../../contexts/templateCenter.js";
import type { MouseEvent, ReactNode } from "react";

const { Meta } = Card;

function TemplateCenterCard<TemplateType extends TemplateCenterAllowedTypes>({
    template,
    renderActions,
    renderTags,
    onSelect,
    grayOutAlreadyExisting,
    onAcknowledgementClick,
}: {
    template: TemplateType["afterPersist"];
    renderActions?: (template: TemplateType["afterPersist"], delegateSelect: (e: any) => void) => ReactNode[];
    renderTags?: (tags: Record<string, string>, template: TemplateType["afterPersist"]) => Record<string, string>;
    onSelect?: (template: TemplateType["afterPersist"]) => void;
    onAcknowledgementClick?: (
        action: CdnMiddlewareConsumerData["afterPersist"]["acknowledgement"]["buttonAction"],
        template: TemplateType["afterPersist"],
    ) => void;
    grayOutAlreadyExisting?: boolean;
}) {
    const { __, _i } = useI18n();
    const { modal } = App.useApp();
    const { isPro, isDemoEnv } = useUpsell();
    const {
        headline,
        subHeadline,
        logoUrl,
        tier,
        consumerData: { tags, isDisabled, isCreated, isIgnored, acknowledgement },
    } = template;

    const { technicalHandlingIntegration } = (template as ClientServiceTemplate["afterPersist"]).consumerData;

    const disabledTranslatedText = __("Disabled");
    const showProBadge = tier === ERcbTier.Pro && (!isPro || isDemoEnv);

    const { open: openProModal, modal: proModal } = useUpsellModal(
        {
            title: __("Want to use %s template?", headline),
            feature: "preset",
            description: `${__(
                "Only a limited number of templates for services and content blockers are available in the %s version of Real Cookie Banner. Get the PRO version now and create a service or content blocker from this template with just one click!",
                (isDemoEnv ? __("Demo") : __("Free")).toLowerCase(),
            )}${
                isDemoEnv
                    ? ""
                    : `

${__(
    "You can create this service yourself in the free version without any restrictions and research the necessary information.",
)}`
            }`,
        },
        // PRO Presets are deactivate on try.devowl.io
        isDemoEnv ? false : undefined,
    );

    const handleClick = (e: MouseEvent<HTMLDivElement, globalThis.MouseEvent>) => {
        // This event is bubbled also for the external URLs table in the modal dialog
        // Check if the click comes directly from the card
        if (!(e.target as HTMLDivElement).closest(".rcb-antd-card,.rcb-template-card-create-link")) {
            return;
        }

        if (acknowledgement) {
            const { paragraphs, accordion, buttonAction, buttonLabel } = acknowledgement;
            const createdModal = modal.info({
                icon: null,
                width: 800,
                closable: true,
                okButtonProps: { style: { display: "none" } },
                content: (
                    <div style={{ textAlign: "center" }}>
                        <img
                            src={template.logoUrl}
                            style={{ display: "block", paddingTop: 15, margin: "auto", height: 176 }}
                        />
                        <h3 style={{ margin: "10px 0 0" }}>{template.headline}</h3>
                        <p style={{ marginTop: 0 }}>{template.subHeadline}</p>
                        <Divider>{__("Special circumstances for this service")}</Divider>
                        {paragraphs.map((paragraph) => (
                            <p key={paragraph} style={{ textAlign: "left" }}>
                                {_i(paragraph, {
                                    strong: <strong />,
                                    u: <u style={{ textDecorationStyle: "dashed" }} />,
                                })}
                            </p>
                        ))}
                        {accordion && (
                            <Collapse
                                style={{ textAlign: "left" }}
                                defaultActiveKey={Object.keys(accordion)[0]}
                                items={Object.keys(accordion).map((key) => ({
                                    key,
                                    label: key,
                                    children: (
                                        <p style={{ margin: 0 }} dangerouslySetInnerHTML={{ __html: accordion[key] }} />
                                    ),
                                }))}
                            />
                        )}
                        {onAcknowledgementClick && (
                            <div style={{ marginTop: 10 }}>
                                <button
                                    className="button button-large button-primary"
                                    onClick={() => {
                                        createdModal.destroy();
                                        onAcknowledgementClick?.(buttonAction, template);
                                    }}
                                >
                                    {buttonLabel}
                                </button>
                            </div>
                        )}
                    </div>
                ),
            });
        } else if (showProBadge) {
            openProModal();
        } else if (!isDisabled) {
            onSelect?.(template);
        }
    };

    const coverImage = <img style={{ width: "90%" }} src={logoUrl} />;
    const useTags = renderTags ? renderTags({ ...tags }, template) : tags;

    return (
        <>
            {proModal}
            <Tooltip
                title={
                    isDisabled ? <span dangerouslySetInnerHTML={{ __html: tags[disabledTranslatedText] }} /> : undefined
                }
            >
                <Card
                    className="rcb-antd-template-card"
                    hoverable={!isDisabled}
                    style={{
                        opacity: isDisabled || (grayOutAlreadyExisting && (isCreated || isIgnored)) ? 0.6 : 1,
                    }}
                    onClick={handleClick}
                    cover={
                        technicalHandlingIntegration ? (
                            <Badge.Ribbon
                                text={
                                    <Tooltip
                                        title={_i(
                                            __(
                                                "The {{strong}}%s{{/strong}} plugin is recommending this service.",
                                                technicalHandlingIntegration.name,
                                            ),
                                            { strong: <strong /> },
                                        )}
                                    >
                                        <div>{__("Integration")}</div>
                                    </Tooltip>
                                }
                            >
                                {coverImage}
                            </Badge.Ribbon>
                        ) : (
                            coverImage
                        )
                    }
                    actions={renderActions ? renderActions(template, handleClick) : []}
                >
                    <Meta
                        title={
                            <span>
                                {showProBadge && <Tag color={UPSELL_TAG_BACKGROUND_COLOR}>PRO</Tag>}
                                {!!tags &&
                                    Object.keys(useTags).map((key) => (
                                        <Tooltip
                                            title={
                                                key === disabledTranslatedText || !tags[key] ? undefined : (
                                                    <span dangerouslySetInnerHTML={{ __html: tags[key] }} />
                                                )
                                            }
                                            key={key}
                                        >
                                            <Tag>{key}</Tag>
                                        </Tooltip>
                                    ))}
                                <br />
                                {headline}
                            </span>
                        }
                        description={subHeadline ? subHeadline : <i>{__("No description")}</i>}
                    />
                </Card>
            </Tooltip>
        </>
    );
}

export { TemplateCenterCard };
