import { WarningOutlined } from "@ant-design/icons";
import { App, Dropdown, Tag } from "antd";
import { observer } from "mobx-react";
import { useEffect } from "react";

import { createCopy } from "@devowl-wp/multilingual";
import type { ListServiceRowAttributes } from "@devowl-wp/react-cookie-banner-admin";
import { ListService, useListServiceProvider } from "@devowl-wp/react-cookie-banner-admin";
import { arrayMove } from "@devowl-wp/react-utils";

import { useConfigHintText } from "../../../hooks/useConfigHintText.js";
import { useRouteCookieGroup } from "../../../hooks/useRouteCookieGroup.js";
import { useStores } from "../../../store/stores.js";
import { _n } from "../../../utils/i18n.js";
import { ConfigContent } from "../content.js";

import type { FC } from "react";

const CookiesList: FC = observer(() => {
    const { message } = App.useApp();
    const {
        optionStore: {
            isOnlyRcbCookieCreated,
            isConsentForwarding,
            isDataProcessingInUnsafeCountries,
            setCookiesViaManager,
            isGcm,
            others: {
                hints: { deleteCookie },
            },
        },
        cookieStore: { unassignedCookies, essentialGroup },
    } = useStores();
    const hintText = useConfigHintText("cookie");
    const { group, addCookieLink, editLink } = useRouteCookieGroup();
    const {
        cookies,
        cookiesCount,
        data: { name: groupName },
    } = group;
    const { busy, sortedCookies, entries } = cookies;

    useEffect(() => {
        group.fetchCookies();
    }, []);

    const [ListServiceContextProvider, listServiceContextValue] = useListServiceProvider(
        {
            isConsentForwarding: isConsentForwarding,
            isDataProcessingInUnsafeCountries: isDataProcessingInUnsafeCountries,
            isOnlyRealCookieBannerServiceCreated: isOnlyRcbCookieCreated,
            isEssential: essentialGroup.key === group.key,
            setCookiesViaManager,
            isGcm,
            groupName,
            busy,
            servicesCount: cookiesCount,
            rows: sortedCookies.map((item) => {
                const { key: id, busy, data, templateModel, technicalDefinitions, isUpdateAvailable } = item;
                const {
                    title: { raw: name },
                    content: { raw: purpose },
                    status,
                    meta: {
                        presetId,
                        codeOptIn,
                        codeOptOut,
                        codeOnPageLoad,
                        uniqueName,
                        deleteTechnicalDefinitionsAfterOptOut,
                        executeCodeOptInWhenNoTagManagerConsentIsGiven,
                        executeCodeOptOutWhenNoTagManagerConsentIsGiven,
                        isEmbeddingOnlyExternalResources,
                        legalBasis,
                        tagManagerOptInEventName,
                        tagManagerOptOutEventName,
                    },
                } = data;

                return {
                    busy,
                    attributes: {
                        id,
                        name,
                        purpose,
                        status: status as ListServiceRowAttributes["status"],
                        codeOptIn,
                        codeOptOut,
                        codeOnPageLoad,
                        uniqueName,
                        deletable: presetId !== "real-cookie-banner",
                        deleteHint: deleteCookie,
                        deleteTechnicalDefinitionsAfterOptOut,
                        executeCodeOptInWhenNoTagManagerConsentIsGiven,
                        executeCodeOptOutWhenNoTagManagerConsentIsGiven,
                        isEmbeddingOnlyExternalResources,
                        isEssential: data["rcb-cookie-group"][0] === essentialGroup.key,
                        legalBasis,
                        presetId,
                        tagManagerOptInEventName,
                        tagManagerOptOutEventName,
                        technicalDefinitions,
                    },
                    avatarUrl: templateModel?.data.logoUrl,
                    isUpdateAvailable,
                    languages: data.multilingual,
                    languageOnClick: async (recordId, { code, id, taxonomies }) => {
                        try {
                            let forwardId: number;
                            let forwardGroupId: number;

                            if (id === false) {
                                const {
                                    id,
                                    taxonomies: { "rcb-cookie-group": groupId },
                                } = await createCopy("rcb-cookie", recordId, code);
                                forwardId = id;
                                [forwardGroupId] = groupId;
                            } else {
                                forwardId = id;
                                [forwardGroupId] = taxonomies["rcb-cookie-group"];
                            }

                            // Open the newly created blocker
                            const url = new URL(window.location.href);
                            url.hash = `#/cookies/${forwardGroupId}/edit/${forwardId}`;
                            url.searchParams.set("lang", code);
                            window.location.href = url.toString();
                        } catch (e) {
                            if (e.responseJSON?.message) {
                                message.error(e.responseJSON.message);
                            } else {
                                throw e;
                            }
                        }
                    },
                };
            }),
        },
        {
            onSort: (_, ids, from, to) => {
                arrayMove(ids, from, to);
                group.cookies.orderCookies(ids);
            },
            onDelete: (_, id) =>
                entries.get(id).delete({
                    force: true,
                }),
            onEdit: (_, id) => {
                window.location.href = editLink(entries.get(id));
            },
            onCreate: () => {
                window.location.href = addCookieLink;
            },
        },
        {
            inherit: [
                "busy",
                "groupName",
                "isEssential",
                "isOnlyRealCookieBannerServiceCreated",
                "rows",
                "servicesCount",
            ],
        },
    );

    return (
        <ConfigContent>
            {unassignedCookies.size > 0 && (
                <div style={{ textAlign: "center", marginBottom: 15 }}>
                    <Dropdown
                        placement="bottomRight"
                        menu={{
                            items: Array.from(unassignedCookies.values()).map(({ id, title }) => ({
                                key: id,
                                label: <a href={`#/cookies/${essentialGroup.key}/edit/${id}`}>{title}</a>,
                            })),
                        }}
                    >
                        <a>
                            <Tag color="red">
                                <WarningOutlined />{" "}
                                {_n(
                                    "One unassigned service",
                                    "%d unassigned services",
                                    unassignedCookies.size,
                                    unassignedCookies.size,
                                )}
                            </Tag>
                        </a>
                    </Dropdown>
                </div>
            )}
            <ListServiceContextProvider value={listServiceContextValue}>
                <ListService />
            </ListServiceContextProvider>
            <p className="description" style={{ maxWidth: 800, margin: "30px auto 0", textAlign: "center" }}>
                {hintText}
            </p>
        </ConfigContent>
    );
});

export { CookiesList };
