import { RightOutlined } from "@ant-design/icons";
import { Avatar, List, Popconfirm, Spin, Tag, Tooltip } from "antd";
import { useMemo, useState } from "react";

import { reactNl2Br } from "@devowl-wp/react-utils";

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

import type { ListContentBlockerRowProps } from "../../../contexts/listContentBlocker.js";
import type { FC } from "react";

const MAX_RULES_ENTRIES = 5;

const ListContentBlockerRow: FC<ListContentBlockerRowProps> = ({
    busy,
    attributes: { id, name, description, status, criteria, services, tcfVendors, rules, isVisual, presetId },
    avatarUrl,
    isUpdateAvailable,
    languages,
    languageOnClick,
}) => {
    const { __ } = useI18n();
    const { isLicensed } = useUpsell();
    const { onEdit, onDelete } = useListContentBlocker();
    const [expandAllHosts, setExpandAllHosts] = useState(false);

    // https://stackoverflow.com/a/5002618/5506547
    const useDescription = useMemo(() => {
        if (description) {
            const element = document.createElement("div");
            element.innerHTML = description;
            return element.textContent;
        }
        return "";
    }, [description]);

    return (
        <List.Item
            itemID={id.toString()}
            actions={[
                <a key="edit" onClick={() => onEdit(id)}>
                    {isUpdateAvailable ? __("Edit and update") : __("Edit")}
                </a>,
                <Popconfirm
                    key="delete"
                    title={__("Are you sure that you want to delete this content blocker?")}
                    placement="bottomRight"
                    onConfirm={() => onDelete(id)}
                    okText={__("Delete")}
                    cancelText={__("Cancel")}
                    overlayStyle={{ maxWidth: 350 }}
                >
                    <a>{__("Delete")}</a>
                </Popconfirm>,
                languages?.length && (
                    <ListMultilingualLanguages
                        recordId={id}
                        languages={languages}
                        key="languages"
                        onClick={languageOnClick}
                    />
                ),
            ].filter(Boolean)}
        >
            <Spin spinning={busy}>
                <List.Item.Meta
                    avatar={
                        avatarUrl ? (
                            <Avatar size="large" src={avatarUrl} shape="square" />
                        ) : (
                            <Avatar size="large" shape="circle">
                                {name.toUpperCase()[0]}
                            </Avatar>
                        )
                    }
                    title={
                        <span>
                            {name}{" "}
                            {status === "draft" ? (
                                <Tag color="orange">{__("Draft")}</Tag>
                            ) : status === "private" ? (
                                <Tag color="red">{__("Disabled")}</Tag>
                            ) : null}
                            {criteria === "services" && services.length === 0 && (
                                <Tag color="red">
                                    {__("No connected services defined")} <RightOutlined /> {__("Disabled")}
                                </Tag>
                            )}
                            {criteria === "tcfVendors" && tcfVendors.length === 0 && (
                                <Tag color="red">
                                    {__("No connected TCF Vendors defined")} <RightOutlined /> {__("Disabled")}
                                </Tag>
                            )}
                            {!!presetId && <Tag>{__("Created from template")}</Tag>}
                            {!!presetId && !avatarUrl && (
                                <Tooltip
                                    title={
                                        isLicensed
                                            ? __(
                                                  "There is no longer a content blocker template for this service. Probably the service has been discontinued. Please look for alternatives!",
                                              )
                                            : __(
                                                  "This content blocker 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 blocker template has been updated to provide current legal and technical information.",
                                    )}
                                >
                                    <Tag color="green">{__("Update available")}</Tag>
                                </Tooltip>
                            )}
                        </span>
                    }
                    description={
                        <div>
                            {!!useDescription && <div>{reactNl2Br(useDescription)}</div>}
                            <div style={{ paddingTop: 5 }}>
                                {__("URLs / Elements to block")}:{" "}
                                {rules.slice(0, expandAllHosts ? rules.length : MAX_RULES_ENTRIES).map((host, i) => (
                                    <Tag key={`${host}-${i}`}>{host}</Tag>
                                ))}
                                {rules.length > MAX_RULES_ENTRIES && !expandAllHosts && (
                                    <Tag onClick={() => setExpandAllHosts(true)}>{__("Show all")}</Tag>
                                )}
                            </div>
                            <div style={{ paddingTop: 5 }}>
                                {__("Visual Content Blocker")}:{" "}
                                <Tag>{isVisual ? __("Yes, if possible") : __("No")}</Tag>
                            </div>
                        </div>
                    }
                />
            </Spin>
        </List.Item>
    );
};

export { ListContentBlockerRow };
