import { App } from "antd";
import { observer } from "mobx-react";
import { useEffect } from "react";

import { createCopy } from "@devowl-wp/multilingual";
import { ListContentBlocker, useListContentBlockerProvider } from "@devowl-wp/react-cookie-banner-admin";
import type { ListContentBlockerRowAttributes } from "@devowl-wp/react-cookie-banner-admin";

import { useConfigHintText } from "../../../hooks/useConfigHintText.js";
import { useRouteBlocker } from "../../../hooks/useRouteBlocker.js";
import { useStores } from "../../../store/stores.js";
import { ConfigContent } from "../content.js";

import type { FC } from "react";

const BlockerList: FC = observer(() => {
    const { message } = App.useApp();
    const { addLink, editLink } = useRouteBlocker();
    const { cookieStore } = useStores();
    const { blockers, cookiesCount, blockersCount } = cookieStore;
    const { busy, sortedBlockers, entries } = blockers;
    const hintText = useConfigHintText("blocker");

    useEffect(() => {
        cookieStore.fetchBlockers();

        // Also fetch cookie groups as they are related to blockers
        cookieStore.fetchGroups();
    }, []);

    const [ListContentBlockerContextProvider, listContentBlockerContextValue] = useListContentBlockerProvider(
        {
            busy,
            serviceCount: cookiesCount,
            contentBlockerCount: blockersCount,
            rows: sortedBlockers.map((item) => {
                const { key: id, busy, data, rules, services, tcfVendors, templateModel, isUpdateAvailable } = item;
                const {
                    title: { raw: name },
                    content: { raw: description },
                    status,
                    meta: { criteria, presetId, isVisual },
                } = data;

                return {
                    busy,
                    attributes: {
                        id,
                        criteria,
                        description,
                        name,
                        isVisual,
                        rules,
                        services,
                        status: status as ListContentBlockerRowAttributes["status"],
                        tcfVendors,
                        presetId,
                    },
                    avatarUrl: templateModel?.data.logoUrl,
                    isUpdateAvailable,
                    languages: data.multilingual,
                    languageOnClick: async (recordId, { code, id }) => {
                        try {
                            const forwardId = id === false ? (await createCopy("rcb-blocker", recordId, code)).id : id;

                            // Open the newly created blocker
                            const url = new URL(window.location.href);
                            url.hash = `#/blocker/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;
                            }
                        }
                    },
                };
            }),
        },
        {
            onDelete: (_, id) =>
                entries.get(id).delete({
                    force: true,
                }),
            onEdit: (_, id) => {
                window.location.href = editLink(entries.get(id));
            },
            onCreate: () => {
                window.location.href = addLink;
            },
        },
        { inherit: ["busy", "contentBlockerCount", "serviceCount", "rows"] },
    );

    return (
        <ConfigContent>
            <ListContentBlockerContextProvider value={listContentBlockerContextValue}>
                <ListContentBlocker />
            </ListContentBlockerContextProvider>
            <p className="description" style={{ maxWidth: 800, margin: "30px auto 0", textAlign: "center" }}>
                {hintText}
            </p>
        </ConfigContent>
    );
});

export { BlockerList };
