import { useEffect, useRef } from 'react'
import {
  Copy, CopyPlus, Trash2, ClipboardPaste, BoxSelect, Ungroup, Maximize2, BringToFront, SendToBack,
  AlignStartVertical, AlignCenterHorizontal, AlignEndVertical,
  AlignStartHorizontal, AlignCenterVertical, AlignEndHorizontal,
  AlignHorizontalSpaceAround, AlignVerticalSpaceAround,
} from 'lucide-react'
import { cn } from '@/lib/utils'

interface MenuAction {
  label: string
  icon: React.ElementType
  shortcut: string
  onClick: () => void
  disabled?: boolean
  dividerBefore?: boolean
}

interface ContextMenuProps {
  position: { x: number; y: number }
  actions: MenuAction[]
  onClose: () => void
  onAlignLeft?: () => void
  onAlignRight?: () => void
  onAlignCenterH?: () => void
  onAlignTop?: () => void
  onAlignBottom?: () => void
  onAlignCenterV?: () => void
  onDistributeH?: () => void
  onDistributeV?: () => void
  canAlign?: boolean
  canDistribute?: boolean
  onGroupSelection?: () => void
  onUngroupSelection?: () => void
  canGroup?: boolean
  canUngroup?: boolean
}

export function ContextMenu({
  position,
  actions,
  onClose,
  onAlignLeft,
  onAlignRight,
  onAlignCenterH,
  onAlignTop,
  onAlignBottom,
  onAlignCenterV,
  onDistributeH,
  onDistributeV,
  canAlign,
  canDistribute,
  onGroupSelection,
  onUngroupSelection,
  canGroup,
  canUngroup,
}: ContextMenuProps) {
  const menuRef = useRef<HTMLDivElement>(null)

  const clampedPosition = { ...position }
  if (typeof window !== 'undefined') {
    const itemCount = actions.length
    const dividerCount = actions.filter(a => a.dividerBefore).length
    const menuWidth = 192
    const menuHeight = itemCount * 36 + dividerCount * 9 + 8
    if (clampedPosition.x + menuWidth > window.innerWidth) {
      clampedPosition.x = window.innerWidth - menuWidth - 8
    }
    if (clampedPosition.y + menuHeight > window.innerHeight) {
      clampedPosition.y = window.innerHeight - menuHeight - 8
    }
  }

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as HTMLElement)) {
        onClose()
      }
    }
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    const handleScroll = () => onClose()

    document.addEventListener('mousedown', handleClickOutside)
    document.addEventListener('keydown', handleEscape)
    document.addEventListener('scroll', handleScroll, true)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
      document.removeEventListener('keydown', handleEscape)
      document.removeEventListener('scroll', handleScroll, true)
    }
  }, [onClose])

  return (
    <div
      ref={menuRef}
      className="fixed z-50 w-48 rounded-lg border border-default bg-card py-1 shadow-lg"
      style={{ left: clampedPosition.x, top: clampedPosition.y }}
    >
      {actions.map((action) => (
        <div key={action.label}>
          {action.dividerBefore && (
            <div className="my-1 border-t border-default" />
          )}
          <button
            onClick={() => {
              action.onClick()
              onClose()
            }}
            disabled={action.disabled}
            className={cn(
              'flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated',
              action.disabled && 'opacity-40 pointer-events-none',
            )}
          >
            <action.icon size={14} />
            <span>{action.label}</span>
            <span className="ml-auto text-[10px] text-muted-foreground">{action.shortcut}</span>
          </button>
        </div>
      ))}

      {canAlign && (
        <>
          <div className="border-t border-default my-1" />
          <div className="px-3 py-0.5 text-[10px] font-medium text-muted uppercase tracking-wider">Align</div>
          <button onClick={() => { onAlignLeft?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignStartVertical size={13} /> <span>Align Left</span>
          </button>
          <button onClick={() => { onAlignCenterH?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignCenterHorizontal size={13} /> <span>Align Center</span>
          </button>
          <button onClick={() => { onAlignRight?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignEndVertical size={13} /> <span>Align Right</span>
          </button>
          <button onClick={() => { onAlignTop?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignStartHorizontal size={13} /> <span>Align Top</span>
          </button>
          <button onClick={() => { onAlignCenterV?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignCenterVertical size={13} /> <span>Align Middle</span>
          </button>
          <button onClick={() => { onAlignBottom?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
            <AlignEndHorizontal size={13} /> <span>Align Bottom</span>
          </button>
          {canDistribute && (
            <>
              <div className="border-t border-default my-1" />
              <div className="px-3 py-0.5 text-[10px] font-medium text-muted uppercase tracking-wider">Distribute</div>
              <button onClick={() => { onDistributeH?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
                <AlignHorizontalSpaceAround size={13} /> <span>Space Horizontally</span>
              </button>
              <button onClick={() => { onDistributeV?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
                <AlignVerticalSpaceAround size={13} /> <span>Space Vertically</span>
              </button>
            </>
          )}
        </>
      )}

      {(canGroup || canUngroup) && (
        <>
          <div className="border-t border-default my-1" />
          {canGroup && (
            <button onClick={() => { onGroupSelection?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
              <BoxSelect size={13} /> <span>Group Selection</span>
            </button>
          )}
          {canUngroup && (
            <button onClick={() => { onUngroupSelection?.(); onClose() }} className="flex w-full items-center gap-2 px-3 py-2 text-xs text-primary hover:bg-elevated">
              <Ungroup size={13} /> <span>Ungroup</span>
            </button>
          )}
        </>
      )}
    </div>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export function getNodeMenuActions(handlers: {
  onCopy: () => void
  onDuplicate: () => void
  onBringToFront: () => void
  onSendToBack: () => void
  onDelete: () => void
}): MenuAction[] {
  return [
    { label: 'Copy', icon: Copy, shortcut: 'Ctrl+C', onClick: handlers.onCopy },
    { label: 'Duplicate', icon: CopyPlus, shortcut: 'Ctrl+D', onClick: handlers.onDuplicate },
    { label: 'Bring to Front', icon: BringToFront, shortcut: ']', onClick: handlers.onBringToFront, dividerBefore: true },
    { label: 'Send to Back', icon: SendToBack, shortcut: '[', onClick: handlers.onSendToBack },
    { label: 'Delete', icon: Trash2, shortcut: 'Del', onClick: handlers.onDelete, dividerBefore: true },
  ]
}

// eslint-disable-next-line react-refresh/only-export-components
export function getCanvasMenuActions(handlers: {
  onPaste: () => void
  onSelectAll: () => void
  onFitView: () => void
  hasClipboard: boolean
}): MenuAction[] {
  return [
    { label: 'Paste', icon: ClipboardPaste, shortcut: 'Ctrl+V', onClick: handlers.onPaste, disabled: !handlers.hasClipboard },
    { label: 'Select All', icon: BoxSelect, shortcut: 'Ctrl+A', onClick: handlers.onSelectAll },
    { label: 'Fit View', icon: Maximize2, shortcut: '⌘⇧F', onClick: handlers.onFitView },
  ]
}
