import { Empty, List, Skeleton } from "antd";
import { useMemo } from "react";

import { ListContentBlockerRow } from "./row.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useListContentBlocker } from "../../../contexts/listContentBlocker.js";

import type { FC } from "react";

const ListContentBlocker: FC = () => {
    const { __ } = useI18n();
    const { busy, serviceCount, contentBlockerCount, rows, onCreate } = useListContentBlocker();

    const dataSourceSkeleton = useMemo(() => {
        const d = [];
        for (let key = 0; key < contentBlockerCount; key++) {
            d.push({ key });
        }
        return d;
    }, [contentBlockerCount]);

    const addText = __("Add content blocker");

    return contentBlockerCount ? (
        <>
            <div className="wp-clearfix">
                <a onClick={onCreate} className="button button-primary right" style={{ marginBottom: 10 }}>
                    {addText}
                </a>
            </div>
            {busy ? (
                <List
                    dataSource={dataSourceSkeleton}
                    renderItem={() => (
                        <List.Item>
                            <Skeleton loading={true} active paragraph={{ rows: 1 }} />
                        </List.Item>
                    )}
                />
            ) : (
                <List>
                    {rows.map((row) => (
                        <ListContentBlockerRow {...row} key={row.attributes.id.toString()} />
                    ))}
                </List>
            )}
        </>
    ) : (
        <Empty
            description={
                serviceCount > 0
                    ? __("You have not yet created a content blocker.")
                    : __(
                          "Because a content blocker must be associated with a service, you must create a service first.",
                      )
            }
        >
            <a className="button button-primary" onClick={onCreate}>
                {addText}
            </a>
        </Empty>
    );
};

export { ListContentBlocker };
