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

import { ListServiceRow } from "./row.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useListService } from "../../../contexts/listService.js";
import { useDndSortable } from "../../../hooks/useDndSortable.js";

import type { FC } from "react";

const ListService: FC = () => {
    const { __, _i } = useI18n();
    const {
        isEssential,
        isOnlyRealCookieBannerServiceCreated,
        busy,
        rows,
        onSort,
        onCreate,
        servicesCount,
        groupName,
    } = useListService();

    const sortableBodyRef = useRef();
    const { SortableContext, SortableRow, DragHandle } = useDndSortable();

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

    const addText = __("Add service");

    // UX: Do not show the list of cookies until the user has created the first cookie
    const showList = isEssential
        ? isOnlyRealCookieBannerServiceCreated
            ? servicesCount > 1
            : servicesCount > 0
        : servicesCount > 0;

    const items = rows.map(({ attributes: { id } }) => `${id}`);

    return showList ? (
        <>
            <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>
                    )}
                />
            ) : (
                <SortableContext
                    items={items}
                    onDragEnd={({ active, over }) => {
                        const from = rows.findIndex((field) => field.attributes.id === +active.id);
                        const to = rows.findIndex((field) => field.attributes.id === +over?.id);
                        onSort(items.map(Number), from, to);
                    }}
                    elementType="div"
                >
                    <List>
                        <div ref={sortableBodyRef}>
                            {rows.map((row, index) => (
                                <SortableRow key={row.attributes.id} data-row-key={`${row.attributes.id}`}>
                                    <ListServiceRow
                                        {...row}
                                        key={row.attributes.id.toString()}
                                        dragHandle={<DragHandle />}
                                    />
                                </SortableRow>
                            ))}
                        </div>
                    </List>
                </SortableContext>
            )}
        </>
    ) : (
        <Empty
            description={_i(__("You have not yet created a service in {{strong}}%s{{/strong}}.", groupName), {
                strong: <strong />,
            })}
        >
            <a className="button button-primary" onClick={onCreate}>
                {addText}
            </a>
        </Empty>
    );
};

export { ListService };
