import { __ } from "@wordpress/i18n";
import { Icon } from "@wordpress/components";
import { dragHandle } from "@wordpress/icons";
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
} from "@dnd-kit/core";
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    useSortable,
    verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";


function SortablePill({ postType }) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: postType.name });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition: isDragging ? undefined : transition,
        opacity: isDragging ? 0.5 : 1,
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className="ecw-pill"
            {...attributes}
            {...listeners}
        >
            <Icon icon={dragHandle} className="ecw-pill__drag-handle" />
            <span className="ecw-pill__label">
                {postType.label} ({postType.count})
            </span>
        </div>
    );
}

export default function PostTypePills({ postTypes, orderedPostTypes, onChange }) {
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: { distance: 8 },
        }),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    // Build ordered list: start with explicitly ordered types, then append remaining types
    const orderedNames = orderedPostTypes || [];
    const orderedObjects = orderedNames
        .map((name) => postTypes.find((pt) => pt.name === name))
        .filter(Boolean);

    const remainingTypes = postTypes.filter(
        (pt) => !orderedNames.includes(pt.name)
    );

    const allOrderedTypes = [...orderedObjects, ...remainingTypes];
    const allOrderedNames = allOrderedTypes.map((pt) => pt.name);

    const handleDragEnd = (event) => {
        const { active, over } = event;

        if (over && active.id !== over.id) {
            const oldIndex = allOrderedNames.indexOf(active.id);
            const newIndex = allOrderedNames.indexOf(over.id);
            const newOrder = arrayMove(allOrderedNames, oldIndex, newIndex);
            onChange(newOrder);
        }
    };

    if (postTypes.length === 0) {
        return (
            <p className='ecw-no-items'>
                {__("No post types found in sitemap.", "cache-autopilot")}
            </p>
        );
    }

    return (
        <div className='ecw-post-type-pills'>
            <div className='ecw-pills-section'>
                <DndContext
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    onDragEnd={handleDragEnd}
                >
                    <SortableContext
                        items={allOrderedNames}
                        strategy={verticalListSortingStrategy}
                    >
                        <div className='ecw-pills-list'>
                            {allOrderedTypes.map((postType) => (
                                <SortablePill
                                    key={postType.name}
                                    postType={postType}
                                />
                            ))}
                        </div>
                    </SortableContext>
                </DndContext>
            </div>
        </div>
    );
}
