import { DownOutlined } from "@ant-design/icons";
import { App, Dropdown, Space } from "antd";
import { useCallback } from "react";

import type { ClientBlockerTemplate, ClientServiceTemplate } from "@devowl-wp/service-cloud-consumer";

import { useI18n } from "../../contexts/i18n.js";
import { TemplateCenterCards } from "../templateCenter/cards.js";

import type { TemplateCenterAllowedTypes } from "../../contexts/templateCenter.js";
import type { FormSettingsValueProps } from "../../types/formSettings.js";
import type { ComponentProps, FC } from "react";

type TypedTemplateCardsProps = ComponentProps<typeof TemplateCenterCards<TemplateCenterAllowedTypes>>;

const ScannerCards: FC<
    Pick<TypedTemplateCardsProps, "templates" | "onSelect"> & {
        dropdownItems: (
            ...args: Parameters<TypedTemplateCardsProps["renderActions"]>
        ) => ComponentProps<typeof Dropdown>["menu"]["items"];
        isTcf?: FormSettingsValueProps["isTcf"];
        onIgnoreToggle: (template: Parameters<TypedTemplateCardsProps["renderActions"]>[0], state: boolean) => void;
    }
> = ({ templates, onSelect, dropdownItems = () => [], isTcf, onIgnoreToggle }) => {
    const { modal } = App.useApp();
    const { __ } = useI18n();

    const handleAcknowledgementClick: TypedTemplateCardsProps["onAcknowledgementClick"] = useCallback(
        (action, template) => {
            if (action === "ignore") {
                onIgnoreToggle(template, true);
            }
        },
        [onIgnoreToggle],
    );

    const handleSelect: TypedTemplateCardsProps["onSelect"] = useCallback(
        (template) => {
            const {
                tcfVendorIds,
                name,
                consumerData: { createAdNetwork },
            } = template as any as ClientServiceTemplate["afterPersist"] & ClientBlockerTemplate["afterPersist"];
            const isTcfTemplate = tcfVendorIds?.length > 0 && !isTcf;

            if (isTcfTemplate) {
                window.location.href = `#/settings/tcf?tcfIntegrationItem=${encodeURIComponent(
                    name,
                )}&navigateAfterTcfActivation=${encodeURIComponent(
                    createAdNetwork
                        ? `#/cookies/tcf-vendors/new?adNetwork=${encodeURIComponent(createAdNetwork)}`
                        : "#/scanner",
                )}`;
            } else {
                onSelect(template);
            }
        },
        [onSelect],
    );

    return (
        <TemplateCenterCards<TemplateCenterAllowedTypes>
            showHidden
            grayOutAlreadyExisting
            templates={templates}
            onSelect={handleSelect}
            onAcknowledgementClick={handleAcknowledgementClick}
            renderTags={useCallback((tags, template) => {
                const { isIgnored, acknowledgement } = template.consumerData;
                if (isIgnored) {
                    tags[acknowledgement ? __("Acknowledged") : __("Ignored")] = "";
                }
                return tags;
            }, [])}
            renderActions={useCallback((template, delegateSelect) => {
                const {
                    tcfVendorIds,
                    consumerData: { isDisabled, isIgnored, acknowledgement },
                } = template as any as ClientServiceTemplate["afterPersist"] & ClientBlockerTemplate["afterPersist"];
                const isTcfTemplate = tcfVendorIds?.length > 0 && !isTcf;

                const createNowLabel = acknowledgement
                    ? __("Show explanation")
                    : isTcfTemplate
                      ? __("Activate TCF")
                      : __("Create now");
                const ignoreLabel = isIgnored
                    ? __("Show recommendation again")
                    : acknowledgement
                      ? __("Acknowledge recommendation")
                      : __("Ignore recommendation");

                return [
                    !isDisabled && (
                        <Dropdown
                            key="dropdown"
                            menu={{
                                items: [
                                    {
                                        key: "create",
                                        label: <a className="rcb-template-card-create-link">{createNowLabel}</a>,
                                    },
                                    ...dropdownItems(template, delegateSelect),
                                    !template.consumerData.isCreated && {
                                        key: "ignore",
                                        label: (
                                            <a
                                                onClick={() => {
                                                    const handleToggle = () => onIgnoreToggle(template, !isIgnored);
                                                    if (isIgnored || acknowledgement) {
                                                        handleToggle();
                                                    } else {
                                                        modal.confirm({
                                                            title: __(
                                                                "Are you sure that you want to ignore this recommendation?",
                                                            ),
                                                            onOk: handleToggle,
                                                            okText: __("Ignore recommendation"),
                                                            cancelText: __("Cancel"),
                                                        });
                                                    }
                                                }}
                                            >
                                                {ignoreLabel}
                                            </a>
                                        ),
                                    },
                                ].filter(Boolean),
                            }}
                        >
                            <Space>
                                {createNowLabel}
                                <DownOutlined />
                            </Space>
                        </Dropdown>
                    ),
                ].filter(Boolean);
            }, [])}
        />
    );
};

export { ScannerCards };
