import React from 'react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { cn } from '@/utils/cn'
import { getDominoDOM, type ImageElement, type Viewport } from '../canvas'
import { LocalIcon } from '../ui/local-icon'

interface ImageActionsToolbarProps {
  element: ImageElement
  viewport: Viewport
  onAction?: (actionId: string) => void
  readOnly?: boolean
}

const TOOLBAR_OFFSET_Y = -20

export const ImageActionsToolbar: React.FC<ImageActionsToolbarProps> = ({
  element,
  viewport,
  onAction,
  readOnly,
}) => {
  const [isVisible, setIsVisible] = React.useState(true)
  const containerRef = React.useRef<HTMLDivElement>(null)
  const { id, x, y, width, height, rotation = 0 } = element
  const { x: vx, y: vy, scale: vs } = viewport

  // Reset visibility when the selected element changes
  React.useEffect(() => {
    setIsVisible(true)
  }, [id])

  React.useEffect(() => {
    const handlePointerDown = (e: PointerEvent) => {
      const dom = getDominoDOM(id)
      if (dom && dom.contains(e.target as Node)) {
        setIsVisible(true)
      }
    }
    // capture 阶段，防止其他地方阻止冒泡导致监听不到
    window.addEventListener('pointerdown', handlePointerDown, { capture: true })
    return () => {
      window.removeEventListener('pointerdown', handlePointerDown, {
        capture: true,
      })
    }
  }, [id])

  const handleAction = React.useCallback(
    (actionId: string) => {
      setIsVisible(false)
      onAction?.(actionId)
    },
    [onAction],
  )

  const actions = [
    {
      id: 'edit-text',
      icon: 'edit-text',
      label: '编辑文字',
      hidden: readOnly,
    },
    {
      id: 'edit-elements',
      icon: 'edit-elements',
      label: '编辑元素',
      hidden: readOnly,
    },
    {
      id: 'partial-redraw',
      icon: 'partial-redraw',
      label: '局部重绘',
      hidden: readOnly,
    },
    {
      id: 'image-matting',
      icon: 'image-matting',
      label: '抠图',
      hidden: readOnly,
    },
    { id: 'download', icon: 'download', isIconOnly: true },
    {
      id: 'more',
      icon: 'more',
      isIconOnly: true,
      hasDropdown: true,
      hidden: readOnly,
    },
  ].filter(action => !action.hidden)

  const dropdownItems = [
    {
      key: 'layer-up',
      label: (
        <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
          <LocalIcon
            name='layer-up'
            className='h-[16px] w-[16px] text-foreground'
          />
          <span className='text-[14px] whitespace-nowrap'>上移一层</span>
        </div>
      ),
    },
    {
      key: 'layer-down',
      label: (
        <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
          <LocalIcon
            name='layer-down'
            className='h-[16px] w-[16px] text-foreground'
          />
          <span className='text-[14px] whitespace-nowrap'>下移一层</span>
        </div>
      ),
    },
    {
      key: 'layer-top',
      label: (
        <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
          <LocalIcon
            name='move-to-top'
            className='h-[16px] w-[16px] text-foreground'
          />
          <span className='text-[14px] whitespace-nowrap'>置于顶层</span>
        </div>
      ),
    },
    {
      key: 'layer-bottom',
      label: (
        <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
          <LocalIcon
            name='move-to-bottom'
            className='h-[16px] w-[16px] text-foreground'
          />
          <span className='text-[14px] whitespace-nowrap'>置于底层</span>
        </div>
      ),
    },
  ]

  if (!isVisible) return null

  return (
    <div
      className='domino-toolbar absolute pointer-events-none z-[10]'
      style={{
        left: x * vs + vx,
        top: (y + TOOLBAR_OFFSET_Y) * vs + vy,
        width: width * vs,
        height: height * vs,
        transform: `rotate(${rotation}deg)`,
      }}
    >
      <div
        ref={containerRef}
        className='editor-floating-panel-soft absolute left-1/2 flex items-center gap-[4px] rounded-full p-[4px] pointer-events-auto'
        style={{
          bottom: '100%',
          marginBottom: '12px',
          transform: 'translate(-50%, 0)',
        }}
      >
        {actions.map(action => {
          const button = (
            <div
              key={action.id}
              className={cn(
                'flex h-[28px] cursor-pointer items-center gap-[6px] rounded-[12px] px-[8px] text-foreground transition-colors hover:bg-accent whitespace-nowrap',
                action.isIconOnly && 'px-[4px]',
              )}
              onClick={() => !action.hasDropdown && handleAction(action.id)}
            >
              <LocalIcon
                name={action.icon}
                className={'w-[16px] h-[16px] text-foreground'}
              />
              {action.label && (
                <span className='text-[14px] font-normal text-foreground'>
                  {action.label}
                </span>
              )}
            </div>
          )

          if (action.hasDropdown) {
            return (
              <DropdownMenu key={action.id}>
                <DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger>
                <DropdownMenuContent side='bottom' align='end'>
                  {dropdownItems.map(item => (
                    <DropdownMenuItem
                      key={item.key}
                      onClick={() => handleAction(item.key)}
                      className='focus:bg-accent data-[highlighted]:bg-accent cursor-pointer'
                    >
                      {item.label}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            )
          }

          return button
        })}
      </div>
    </div>
  )
}
