import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Trash2, GripVertical, ChevronDown } from 'lucide-react'
import { useState } from 'react'
import BlockEditor from './BlockTypeEditor'

export default function BlockItem({ block, onUpdate, onDelete }) {
  const [expanded, setExpanded] = useState(true)
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: block.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  }

  const blockTypeLabels = {
    paragraph: '📝 Paragraph',
    heading: '📌 Heading',
    image: '🖼️ Image',
    code: '💻 Code',
    quote: '💬 Quote',
    divider: '━━ Divider',
    info: 'ℹ️ Info Box',
    warning: '⚠️ Warning',
    error: '❌ Error',
    success: '✅ Success',
    list: '📋 List',
    table: '📊 Table',
    cta: '🎯 CTA Button',
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className="bg-gray-50 border border-gray-300 rounded-lg overflow-hidden"
    >
      <div className="flex items-center gap-3 p-4 bg-gray-100 cursor-move" {...attributes} {...listeners}>
        <GripVertical size={18} className="text-gray-400" />
        <span className="flex-1 font-medium text-gray-700">{blockTypeLabels[block.type] || block.type}</span>
        <button
          onClick={() => setExpanded(!expanded)}
          className="p-1 hover:bg-gray-300 rounded"
        >
          <ChevronDown
            size={18}
            className={`transition ${expanded ? 'rotate-180' : ''}`}
          />
        </button>
        <button
          onClick={() => onDelete(block.id)}
          className="p-1 text-red-600 hover:bg-red-100 rounded"
        >
          <Trash2 size={18} />
        </button>
      </div>

      {expanded && (
        <div className="p-4">
          <BlockEditor
            block={block}
            onChange={(content) => onUpdate(block.id, content)}
          />
        </div>
      )}
    </div>
  )
}
