import { Checkbox, Popconfirm, Radio, Space, Tag } from "antd";
import { useMemo, useState } from "react";

import { useI18n } from "../../../contexts/i18n.js";
import { useListTcfVendor } from "../../../contexts/listTcfVendor.js";

import type { ListTcfVendorContext } from "../../../contexts/listTcfVendor.js";
import type { FC } from "react";

const ListTcfNetworkItem: FC<
    ListTcfVendorContext["contextValue"]["adNetworks"][0] & {
        onCreate: (_: {
            adNetwork: ListTcfVendorContext["contextValue"]["adNetworks"][0];
            list: ListTcfVendorContext["contextValue"]["adNetworks"][0]["lists"][0];
        }) => Promise<void>;
    }
> = (adNetwork) => {
    const contextValue = useListTcfVendor();
    const { view, rows } = contextValue;
    const { __, _n } = useI18n();
    const {
        name,
        description,
        provider,
        lists,
        hasRealTimeApi,
        updatedAt,
        createContentBlockerForVendorId,
        onCreateOrEditContentBlocker,
        onCreate,
    } = adNetwork;
    const [selectedItem, setSelectedItem] = useState<(typeof lists)[0]["name"]>(
        () => lists.filter(({ isRecommended, name }) => isRecommended && name)[0]?.name,
    );
    const vendorWithBlocker = useMemo(
        () =>
            view === "vendors"
                ? rows.filter(
                      ({ vendor: { id }, blocker }) => id === createContentBlockerForVendorId && blocker !== false,
                  )[0]
                : undefined,
        [view, rows, createContentBlockerForVendorId],
    );
    const [isCreateContentBlocker, setIsCreateContentBlocker] = useState(
        !!onCreateOrEditContentBlocker && !vendorWithBlocker,
    );
    const { lang } = document.documentElement;
    const [selectedItemObject] = lists.filter(({ name }) => name === selectedItem);

    return (
        <Space direction="vertical">
            <p className="description">
                {description}
                <br />
                <br />
                {__(
                    "Only advertising partners to whom your website visits have consented can participate in the auction. For advertising partners who require consent in accordance with the TCF standard, the respective TCF vendors must be configured.",
                )}
                <br />
                <br />
                {__("You can automatically import these lists of TCF vendor configurations:")}
            </p>
            <Radio.Group value={selectedItem} onChange={(e) => setSelectedItem(e.target.value)}>
                <Space direction="vertical">
                    {lists.map(({ name, description, isRecommended, vendorIds: { length } }) => (
                        <Radio value={name} key={name}>
                            <div>
                                {name} ({_n("%d TCF vendor", "%d TCF vendors", length, length)}){" "}
                                {isRecommended && <Tag color="blue">{__("Recommended")}</Tag>}
                            </div>
                            <p className="description">{description}</p>
                        </Radio>
                    ))}
                </Space>
            </Radio.Group>
            <p className="description">
                <i>
                    {__("Last updated: %s", new Date(updatedAt).toLocaleDateString(lang))}
                    &nbsp;&bull;&nbsp;
                    {!hasRealTimeApi && __("%s does not offer an API for real-time updates.", provider)}
                </i>
            </p>
            {onCreateOrEditContentBlocker && !vendorWithBlocker && (
                <Checkbox
                    checked={isCreateContentBlocker}
                    onChange={(e) => setIsCreateContentBlocker(e.target.checked)}
                >
                    {__(
                        'Create content blocker for %s (blocks scripts until consent for purpose "Store and/or access information on a device" is given for this TCF vendors)',
                        name,
                    )}
                </Checkbox>
            )}
            <div style={{ textAlign: "right" }}>
                {selectedItemObject && (
                    <Popconfirm
                        title={
                            <>
                                {__(
                                    "After activating the TCF vendors, I will check the information for each activated TCF vendor in the TCF vendor configuration myself and correct any information that does not match my use case.",
                                )}
                                {isCreateContentBlocker && (
                                    <>
                                        <br />
                                        <br />
                                        {__(
                                            "In addition, I'll checked the information in the content blocker  myself for correctness and completeness and add missing information or corrected information that does not fit my use case. I am aware that the manufacturer of Real Cookie Banner cannot take any liability in this respect.",
                                        )}
                                    </>
                                )}
                            </>
                        }
                        overlayInnerStyle={{ maxWidth: 300 }}
                        placement="bottomLeft"
                        onConfirm={async () => {
                            await onCreate({
                                adNetwork,
                                list: selectedItemObject,
                            });

                            if (isCreateContentBlocker && !vendorWithBlocker) {
                                setTimeout(() => {
                                    onCreateOrEditContentBlocker();
                                }, 0);
                            }
                        }}
                        okText={__("Create")}
                        cancelText={__("Cancel")}
                    >
                        <a className="button button-primary">{__("Create TCF vendor configurations")}</a>
                    </Popconfirm>
                )}
            </div>
        </Space>
    );
};

export { ListTcfNetworkItem };
