import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { ListItemText, MenuItem } from '@mui/material'
import type { TableColumn } from '../../table/types'

export interface SortableColumnItemProps {
  column: TableColumn
}

/**
 * A draggable menu item for column reordering.
 * Uses @dnd-kit/sortable for drag-and-drop functionality.
 */
export function SortableColumnItem({ column }: SortableColumnItemProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: column.id })

  const style = {
    transform: CSS.Transform.toString(
      transform ? { ...transform, x: 0 } : null,
    ),
    transition,
    opacity: isDragging ? 0.5 : 1,
    cursor: isDragging ? 'grabbing' : 'grab',
  }

  return (
    <MenuItem
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      role='menuitem'
      tabIndex={0}
      sx={{
        '&:focus-visible': {
          outline: (theme) => `2px solid ${theme.palette.primary.main}`,
          outlineOffset: -2,
        },
      }}
    >
      <ListItemText>{column.label}</ListItemText>
    </MenuItem>
  )
}
