import React, { useState, useEffect } from 'react'
import type { ArtboardElement } from '../canvas'
import { useDominoStore } from '../canvas'
import { LocalIcon } from '../ui/local-icon'

interface ArtboardActionsToolbarProps {
  element: ArtboardElement
  onAction?: (actionId: string) => void
}

const TOOLBAR_OFFSET_Y = -20

export const ArtboardActionsToolbar: React.FC<ArtboardActionsToolbarProps> = ({
  element,
  onAction,
}) => {
  const viewport = useDominoStore(state => state.viewport)
  const { x, y, width, height, rotation = 0 } = element
  const { x: vx, y: vy, scale: vs } = viewport
  const updateElement = useDominoStore(state => state.updateElement)

  const [w, setW] = useState<number | string>(Math.round(width))
  const [h, setH] = useState<number | string>(Math.round(height))

  const lastElementIdRef = React.useRef(element.id)

  useEffect(() => {
    if (lastElementIdRef.current !== element.id) {
      setW(Math.round(width))
      setH(Math.round(height))
      lastElementIdRef.current = element.id
    }
  }, [element.id, width, height])

  const handleWidthChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = parseInt(e.target.value)
    if (!isNaN(val)) {
      setW(val)
      updateElement(element.id, { width: val })
    } else {
      setW(e.target.value)
    }
  }

  const handleHeightChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = parseInt(e.target.value)
    if (!isNaN(val)) {
      setH(val)
      updateElement(element.id, { height: val })
    } else {
      setH(e.target.value)
    }
  }

  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
        className='editor-floating-panel-soft absolute left-1/2 flex items-center gap-[8px] rounded-full p-[6px] pointer-events-auto'
        style={{
          bottom: '100%',
          marginBottom: '12px',
          transform: 'translate(-50%, 0)',
        }}
        onClick={e => e.stopPropagation()}
        onPointerDown={e => e.stopPropagation()}
      >
        <div className='editor-toolbar-chip flex h-[32px] items-center gap-[4px] rounded-full px-[12px] focus-within:ring-2 focus-within:ring-ring/60'>
          <span className='select-none text-[12px] font-medium text-[var(--editor-text-muted)]'>
            W
          </span>
          <input
            type='number'
            value={w}
            onChange={handleWidthChange}
            className='w-[44px] bg-transparent text-[12px] text-foreground outline-none tabular-nums [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
            onKeyDown={e => {
              if (e.key === 'Enter') e.currentTarget.blur()
            }}
          />
        </div>
        <div className='editor-toolbar-chip flex h-[32px] items-center gap-[4px] rounded-full px-[12px] focus-within:ring-2 focus-within:ring-ring/60'>
          <span className='select-none text-[12px] font-medium text-[var(--editor-text-muted)]'>
            H
          </span>
          <input
            type='number'
            value={h}
            onChange={handleHeightChange}
            className='w-[44px] bg-transparent text-[12px] text-foreground outline-none tabular-nums [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
            onKeyDown={e => {
              if (e.key === 'Enter') e.currentTarget.blur()
            }}
          />
        </div>
        <div
          className='ml-4px flex h-[32px] w-[32px] cursor-pointer items-center justify-center rounded-full text-foreground transition-colors hover:bg-accent'
          onClick={() => onAction?.('download')}
        >
          <LocalIcon
            name='download'
            className='h-[18px] w-[18px]'
          />
        </div>
      </div>
    </div>
  )
}
