import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { ListItemText, MenuItem } from '@mui/material'
import { DragIndicator as DragIndicatorIcon } from '@mui/icons-material'
import type { ComponentType, ReactNode } from 'react'
import type { SvgIconProps } from '@mui/material'
import { styles } from './style'

export interface SortableColumnItemProps {
  id: string
  label: ReactNode
  dragHandleIcon?: ComponentType<SvgIconProps>
}

/**
 * Draggable menu item used inside ChangeColumn's `<DndContext>`. Wraps a
 * MUI `<MenuItem>` so it inherits keyboard / theming behavior, and exposes
 * the dnd-kit listeners on the whole row so the user can grab anywhere on
 * the row to reorder.
 */
export function SortableColumnItem({
  id,
  label,
  dragHandleIcon: HandleIcon = DragIndicatorIcon,
}: SortableColumnItemProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id })

  const transformStyle = {
    transform: CSS.Transform.toString(
      transform ? { ...transform, x: 0 } : null,
    ),
    transition,
  }

  return (
    <MenuItem
      ref={setNodeRef}
      style={transformStyle}
      {...attributes}
      {...listeners}
      role='menuitem'
      tabIndex={0}
      sx={{ ...styles.item, ...(isDragging && styles.itemDragging) }}
    >
      <HandleIcon sx={styles.dragHandle} />
      <ListItemText>{label}</ListItemText>
    </MenuItem>
  )
}
