import { useState } from 'react'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { Plus, GripVertical } from 'lucide-react'
import BlockItem from './BlockItem'
import BlockTypeSelector from './BlockTypeSelector'

export default function BlockEditor({ blocks, onChange }) {
  const [showTypeSelector, setShowTypeSelector] = useState(false)

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  )

  const handleDragEnd = (event) => {
    const { active, over } = event
    if (over && active.id !== over.id) {
      const oldIndex = blocks.findIndex(b => b.id === active.id)
      const newIndex = blocks.findIndex(b => b.id === over.id)
      onChange(arrayMove(blocks, oldIndex, newIndex))
    }
  }

  const addBlock = (type) => {
    const newBlock = {
      id: Date.now(),
      type,
      content: {},
    }
    onChange([...blocks, newBlock])
    setShowTypeSelector(false)
  }

  const deleteBlock = (id) => {
    onChange(blocks.filter(b => b.id !== id))
  }

  const updateBlock = (id, content) => {
    onChange(blocks.map(b => b.id === id ? { ...b, content } : b))
  }

  return (
    <div className="bg-white rounded-lg p-6 shadow-md">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-bold text-gray-900">Content Blocks</h2>
        <button
          onClick={() => setShowTypeSelector(!showTypeSelector)}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          <Plus size={18} /> Add Block
        </button>
      </div>

      {showTypeSelector && (
        <BlockTypeSelector onSelect={addBlock} onClose={() => setShowTypeSelector(false)} />
      )}

      {blocks.length > 0 ? (
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext items={blocks.map(b => b.id)} strategy={verticalListSortingStrategy}>
            <div className="space-y-3">
              {blocks.map((block) => (
                <BlockItem
                  key={block.id}
                  block={block}
                  onUpdate={updateBlock}
                  onDelete={deleteBlock}
                />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      ) : (
        <p className="text-center text-gray-500 py-8">No blocks yet. Add one to get started.</p>
      )}
    </div>
  )
}
