import { Lecture } from "packages/common/dist";
import { useCallback } from "react";
import { LectureFormItem } from "./LectureFormItem";
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 LectureFormListProps {
    lectures: Lecture[];
    sectionId: string;
    onUpdate: (lectures: Lecture[]) => void;
}

interface SortableItemProps {
    lecture: Lecture;
    index: number;
    onUpdate: (lecture: Lecture) => void;
    onDelete: (lectureId: string) => void;
}

function SortableItem({ lecture, index, onUpdate, onDelete }: SortableItemProps) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: lecture.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' : ''}`}
        >
            <LectureFormItem
                lecture={lecture}
                index={index}
                onUpdate={onUpdate}
                onDelete={onDelete}
            />
            <Button
                size="xs"
                leftIcon={

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

            </Button>
        </div>
    );
}

export function LectureFormList({ lectures, sectionId, onUpdate }: LectureFormListProps) {
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8,
            },
        }),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    const handleUpdate = useCallback((updatedLecture: Lecture) => {
        onUpdate(lectures.map(l => l.id === updatedLecture.id ? updatedLecture : l));
    }, [lectures, onUpdate]);

    const handleDelete = useCallback((lectureId: string) => {
        onUpdate(lectures.filter(l => l.id !== lectureId));
    }, [lectures, onUpdate]);

    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event;
        if (over && active.id !== over.id) {
            const oldIndex = lectures.findIndex((lecture) => lecture.id === active.id);
            const newIndex = lectures.findIndex((lecture) => lecture.id === over.id);
            const newLectures = [...lectures];
            const [removed] = newLectures.splice(oldIndex, 1);
            newLectures.splice(newIndex, 0, removed);
            onUpdate(newLectures);
        }
    };

    if (lectures.length === 0) {
        return (
            <div className="select-none flex items-center justify-center text-gray-500">
                暂无课程内容
            </div>
        );
    }

    return (
        <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
        >
            <SortableContext
                items={lectures.map(lecture => lecture.id)}
                strategy={verticalListSortingStrategy}
            >
                <div className="space-y-3">
                    {lectures.map((lecture, index) => (
                        <SortableItem
                            key={lecture.id}
                            lecture={lecture}
                            index={index}
                            onUpdate={handleUpdate}
                            onDelete={handleDelete}
                        />
                    ))}
                </div>
            </SortableContext>
        </DndContext>
    );
}