"use client"

import React, { ReactNode } from "react"
import { DragDropContext, Droppable, Draggable, DropResult } from "@hello-pangea/dnd"
import { cn } from '../../lib/utils'

export interface DraggableListProps<T> {
  items: T[]
  onReorder: (items: T[]) => void
  renderItem: (item: T, index: number) => ReactNode
  keyExtractor: (item: T) => string
  direction?: "vertical" | "horizontal"
  className?: string
  droppableId?: string
  disabled?: boolean
}

export function DraggableList<T>({
  items,
  onReorder,
  renderItem,
  keyExtractor,
  direction = "vertical",
  className,
  droppableId = "draggable-list",
  disabled = false,
}: DraggableListProps<T>) {
  const handleDragEnd = (result: DropResult) => {
    if (!result.destination || disabled) {
      return
    }

    const sourceIndex = result.source.index
    const destinationIndex = result.destination.index

    if (sourceIndex === destinationIndex) {
      return
    }

    const newItems = Array.from(items)
    const [reorderedItem] = newItems.splice(sourceIndex, 1)
    newItems.splice(destinationIndex, 0, reorderedItem)

    onReorder(newItems)
  }

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable 
        droppableId={droppableId} 
        direction={direction}
        isDropDisabled={disabled}
      >
        {(provided, snapshot) => (
          <div
            {...provided.droppableProps}
            ref={provided.innerRef}
            className={cn(
              "space-y-2",
              direction === "horizontal" && "flex space-y-0 space-x-2",
              snapshot.isDraggingOver && "bg-muted/50 rounded-lg",
              className
            )}
          >
            {items.map((item, index) => (
              <Draggable
                key={keyExtractor(item)}
                draggableId={keyExtractor(item)}
                index={index}
                isDragDisabled={disabled}
              >
                {(provided, snapshot) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    className={cn(
                      "transition-all duration-200",
                      snapshot.isDragging && "rotate-2 scale-105 shadow-lg z-50",
                      disabled && "cursor-not-allowed opacity-50"
                    )}
                    style={{
                      ...provided.draggableProps.style,
                      transform: snapshot.isDragging
                        ? provided.draggableProps.style?.transform
                        : "none",
                    }}
                  >
                    {renderItem(item, index)}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  )
}