import { DeleteOutlined, InfoCircleOutlined } from "@ant-design/icons";
import { Avatar, List, Popconfirm, Spin, Tag, Tooltip, Typography } from "antd";

import { getManagerDependingVariables } from "@devowl-wp/cookie-consent-web-client";
import { getCookieTypeLocalizationMap } from "@devowl-wp/react-cookie-banner";
import { reactNl2Br } from "@devowl-wp/react-utils";

import { useI18n } from "../../../contexts/i18n.js";
import { useListService } from "../../../contexts/listService.js";
import { useUpsell } from "../../../contexts/upsell.js";
import { ListMultilingualLanguages } from "../../common/listMultilingualLanguages.js";

import type { ListServiceRowProps } from "../../../contexts/listService.js";
import type { FC, ReactNode } from "react";

const { Paragraph } = Typography;

const ListServiceRow: FC<
    ListServiceRowProps & {
        dragHandle: ReactNode;
    }
> = ({
    busy,
    attributes: {
        isEssential,
        deleteHint,
        deletable,
        id,
        name,
        purpose,
        status,
        isEmbeddingOnlyExternalResources,
        uniqueName,
        technicalDefinitions,
        legalBasis,
        tagManagerOptInEventName,
        tagManagerOptOutEventName,
        executeCodeOptInWhenNoTagManagerConsentIsGiven,
        executeCodeOptOutWhenNoTagManagerConsentIsGiven,
        codeOptIn,
        codeOptOut,
        deleteTechnicalDefinitionsAfterOptOut,
        codeOnPageLoad,
        presetId,
    },
    avatarUrl,
    isUpdateAvailable,
    languages,
    languageOnClick,
    dragHandle,
}) => {
    const { __ } = useI18n();
    const { isLicensed } = useUpsell();
    const { isConsentForwarding, onEdit, onDelete, setCookiesViaManager, isGcm } = useListService();
    const cookieTypeLocalized = getCookieTypeLocalizationMap();
    const firstTechnicalDefinition = technicalDefinitions?.[0];

    const { managerLabel, serviceIsManager, features } = getManagerDependingVariables(setCookiesViaManager, {
        isGcm,
        presetId,
    });

    return (
        <List.Item
            itemID={id.toString()}
            actions={[
                <a key="edit" onClick={() => onEdit(id)}>
                    {isUpdateAvailable ? __("Edit and update") : __("Edit")}
                </a>,
                deletable ? (
                    <Popconfirm
                        key="delete"
                        title={reactNl2Br(
                            [__("Are you sure you want to delete this service?"), ...deleteHint].join("\n\n"),
                        )}
                        placement="bottomRight"
                        onConfirm={() => onDelete(id)}
                        okText={__("Delete")}
                        cancelText={__("Cancel")}
                        overlayStyle={{ maxWidth: 350 }}
                    >
                        <a style={{ cursor: "pointer" }}>{__("Delete")}</a>
                    </Popconfirm>
                ) : (
                    <Tooltip
                        placement="topRight"
                        arrow={{ pointAtCenter: true }}
                        overlay={__(`The "%s" service cannot be deleted.`, name)}
                    >
                        <a style={{ opacity: 0.5 }}>{__("Delete")}</a>
                    </Tooltip>
                ),
                languages?.length && (
                    <ListMultilingualLanguages
                        recordId={id}
                        languages={languages}
                        key="languages"
                        onClick={languageOnClick}
                    />
                ),
                <a key="drag">{dragHandle}</a>,
            ].filter(Boolean)}
        >
            <Spin spinning={busy}>
                <List.Item.Meta
                    avatar={
                        avatarUrl ? (
                            <Avatar size="large" src={avatarUrl} shape="square" />
                        ) : (
                            <Avatar
                                size="large"
                                style={{
                                    backgroundColor: isEmbeddingOnlyExternalResources
                                        ? "#4ea29a"
                                        : cookieTypeLocalized[firstTechnicalDefinition.type].backgroundColor,
                                }}
                            >
                                {isEmbeddingOnlyExternalResources
                                    ? __("None")
                                    : cookieTypeLocalized[firstTechnicalDefinition.type].abbr}
                            </Avatar>
                        )
                    }
                    title={
                        <span>
                            {name}{" "}
                            {status === "draft" ? (
                                <Tag color="orange">{__("Draft")}</Tag>
                            ) : status === "private" ? (
                                <Tag color="red">{__("Disabled")}</Tag>
                            ) : null}
                            {!!isEmbeddingOnlyExternalResources && <Tag>{__("No technical cookies")}</Tag>}
                            {!isEssential && legalBasis === "legitimate-interest" && (
                                <Tag>{__("Legitimate interest (Opt-out)")}</Tag>
                            )}
                            {isEssential && legalBasis === "legal-requirement" && (
                                <Tag>{__("Compliance with a legal obligation")}</Tag>
                            )}
                            {!!presetId && <Tag>{__("Created from template")}</Tag>}
                            {!!presetId && !avatarUrl && (
                                <Tooltip
                                    title={
                                        isLicensed
                                            ? __(
                                                  "There is no longer a service template for this service. Probably the service has been discontinued. Please look for alternatives!",
                                              )
                                            : __(
                                                  "This service was created from a template. As you do not have a license activated at the moment, updates that are potentially available cannot be downloaded.",
                                              )
                                    }
                                >
                                    <Tag color="red">
                                        {isLicensed ? __("No longer supported") : __("Possibly outdated")}
                                    </Tag>
                                </Tooltip>
                            )}
                            {!!isUpdateAvailable && (
                                <Tooltip
                                    title={__(
                                        "The service template has been updated to provide current legal and technical information.",
                                    )}
                                >
                                    <Tag color="green">{__("Update available")}</Tag>
                                </Tooltip>
                            )}
                        </span>
                    }
                    description={
                        <div>
                            {!!purpose && (
                                <Paragraph style={{ color: "inherit", marginBottom: 0 }} ellipsis={{ rows: 3 }}>
                                    {reactNl2Br(purpose)}
                                </Paragraph>
                            )}
                            {!!(codeOptIn || codeOptOut || codeOnPageLoad) && (
                                <div style={{ paddingTop: 5 }}>
                                    {__("Executes code on")}:{" "}
                                    {!!codeOptIn && (
                                        <Tag>
                                            {__("Opt-in")}
                                            {features.executeCodeWhenNoTagManagerConsentIsGiven &&
                                                executeCodeOptInWhenNoTagManagerConsentIsGiven && (
                                                    <Tooltip
                                                        title={__(
                                                            "Only run this script if the user has not consented to use %s",
                                                            managerLabel,
                                                        )}
                                                    >
                                                        <span>
                                                            {" "}
                                                            <InfoCircleOutlined />
                                                        </span>
                                                    </Tooltip>
                                                )}
                                        </Tag>
                                    )}
                                    {(!!codeOptOut || deleteTechnicalDefinitionsAfterOptOut) && !isEssential && (
                                        <Tag>
                                            {__("Opt-out")}
                                            {features.executeCodeWhenNoTagManagerConsentIsGiven !== false &&
                                                executeCodeOptOutWhenNoTagManagerConsentIsGiven && (
                                                    <Tooltip
                                                        title={__(
                                                            "Only run this script if the user has not consented to use %s",
                                                            managerLabel,
                                                        )}
                                                    >
                                                        <span>
                                                            {" "}
                                                            <InfoCircleOutlined />
                                                        </span>
                                                    </Tooltip>
                                                )}
                                            {deleteTechnicalDefinitionsAfterOptOut && (
                                                <Tooltip
                                                    title={__(
                                                        "Delete all first-party cookies after opt-out. First-party cookies are only cookies that are set by or for this domain.",
                                                    )}
                                                >
                                                    <span>
                                                        {" "}
                                                        <DeleteOutlined />
                                                    </span>
                                                </Tooltip>
                                            )}
                                        </Tag>
                                    )}
                                    {!!codeOnPageLoad && <Tag>{__("Page load")}</Tag>}
                                </div>
                            )}
                            {!!managerLabel && (
                                <div style={{ paddingTop: 5 }}>
                                    {serviceIsManager ? (
                                        <span>
                                            {__("Opt-in script loads")}: <Tag>{managerLabel}</Tag>
                                        </span>
                                    ) : (
                                        features.events && (
                                            <span>
                                                {__("%s Events", managerLabel)}:{" "}
                                                <Tag>
                                                    <strong>{__("Opt-in")}: </strong>
                                                    {tagManagerOptInEventName || __("None")}
                                                </Tag>
                                                <Tag>
                                                    <strong>{__("Opt-out")}: </strong>
                                                    {tagManagerOptOutEventName || __("None")}
                                                </Tag>
                                            </span>
                                        )
                                    )}
                                </div>
                            )}
                            {isConsentForwarding && (
                                <div style={{ paddingTop: 5 }}>
                                    {__("Consent Forwarding Unique Name")}: <Tag>{uniqueName}</Tag>
                                </div>
                            )}
                        </div>
                    }
                />
            </Spin>
        </List.Item>
    );
};

export { ListServiceRow };
