import { Section } from "@nice/common";
import { SectionFormItem } from "./SectionFormItem";
import { Bars3Icon } from "@heroicons/react/24/outline";
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
    DragEndEvent,
} from "@dnd-kit/core";
import {
    SortableContext,
    sortableKeyboardCoordinates,
    verticalListSortingStrategy,
    useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button } from "@web/src/components/common/element/Button";

interface SectionFormListProps {
    sections: Section[];
    setSections: React.Dispatch<React.SetStateAction<Section[]>>;
}

interface SortableItemProps {
    section: Section;
    index: number;
    onUpdate: (section: Section) => void;
    onDelete: (sectionId: string) => void;
}

function SortableItem({ section, index, onUpdate, onDelete }: SortableItemProps) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: section.id });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        zIndex: isDragging ? 1 : 0,
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className={`flex items-center  relative ${isDragging ? 'opacity-50' : ''}`}
        >
            <SectionFormItem
                key={section.id}
                section={section}
                index={index}
                onUpdate={onUpdate}
                onDelete={onDelete}
            />
            <Button
                size="sm"
                leftIcon={

                    <Bars3Icon
                    />
                } variant="ghost" className="absolute   -right-10 cursor-grab active:cursor-grabbing " title="拖拽排序"
                {...attributes}
                {...listeners}
            ></Button>

        </div>
    );
}

export default function SectionFormList({ sections, setSections }: SectionFormListProps) {
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8, // 8px的移动距离后才开始拖拽
            },
        }),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    const updateSection = (updatedSection: Section) => {
        setSections(prev => prev.map(section =>
            section.id === updatedSection.id ? updatedSection : section
        ));
    };

    const deleteSection = (sectionId: string) => {
        setSections(prev => prev.filter(section => section.id !== sectionId));
    };

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

        if (over && active.id !== over.id) {
            setSections((prev) => {
                const oldIndex = prev.findIndex((section) => section.id === active.id);
                const newIndex = prev.findIndex((section) => section.id === over.id);

                const newSections = [...prev];
                const [removed] = newSections.splice(oldIndex, 1);
                newSections.splice(newIndex, 0, removed);

                return newSections;
            });
        }
    };

    return (
        <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
        >
            <SortableContext
                items={sections.map(section => section.id)}
                strategy={verticalListSortingStrategy}
            >
                <div className="space-y-4">
                    {sections.map((section, index) => (
                        <SortableItem
                            key={section.id}
                            section={section}
                            index={index}
                            onUpdate={updateSection}
                            onDelete={deleteSection}
                        />
                    ))}
                </div>
            </SortableContext>
        </DndContext>
    );
}