import React from 'react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { cn } from '@/utils/cn'
import type { TextElement, Viewport } from '../canvas'
import { useDominoStore, useDominoStoreInstance } from '../canvas'
import { useLocalFonts } from '../../hooks/use-local-fonts'
import { Icon } from '../ui/icon'
import { LocalIcon } from '../ui/local-icon'

interface TextToolbarProps {
  element: TextElement
  viewport: Viewport
  readOnly?: boolean
}

const FONT_SIZES = [12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80]

const ALIGNMENTS = [
  {
    id: 'left',
    icon: () => (
      <LocalIcon
        name='image-editor-text-align-left'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '左对齐',
  },
  {
    id: 'center',
    icon: () => (
      <LocalIcon
        name='image-editor-text-align-center'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '居中对齐',
  },
  {
    id: 'right',
    icon: () => (
      <LocalIcon
        name='image-editor-text-align-right'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '右对齐',
  },
] as const

const LAYER = [
  {
    id: 'layer-up',
    icon: () => (
      <LocalIcon
        name='image-editor-text-layer-up'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '上移一层',
  },
  {
    id: 'layer-down',
    icon: () => (
      <LocalIcon
        name='image-editor-text-layer-down'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '下移一层',
  },
  {
    id: 'layer-top',
    icon: () => (
      <LocalIcon
        name='move-to-top'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '置于顶层',
  },
  {
    id: 'layer-bottom',
    icon: () => (
      <LocalIcon
        name='move-to-bottom'
        className='w-[16px] h-[16px] text-foreground'
      />
    ),
    label: '置于底层',
  },
] as const

export const TextToolbar: React.FC<TextToolbarProps> = ({
  element,
  viewport,
  readOnly,
}) => {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const store = useDominoStoreInstance()
  const { x, y, width, rotation = 0 } = element
  const { x: vx, y: vy, scale: vs } = viewport
  const updateElement = useDominoStore(state => state.updateElement)
  const moveElementUp = useDominoStore(state => state.moveElementUp)
  const moveElementDown = useDominoStore(state => state.moveElementDown)
  const moveElementToTop = useDominoStore(state => state.moveElementToTop)
  const moveElementToBottom = useDominoStore(state => state.moveElementToBottom)

  const handleUpdate = (updates: Partial<TextElement>) => {
    store.getState().takeSnapshot()
    updateElement(element.id, updates)
  }

  const handleUpdateLayer = (
    key: 'layer-up' | 'layer-down' | 'layer-top' | 'layer-bottom',
  ) => {
    const actions = {
      'layer-up': moveElementUp,
      'layer-down': moveElementDown,
      'layer-top': moveElementToTop,
      'layer-bottom': moveElementToBottom,
    }
    const handle = actions[key]
    store.getState().takeSnapshot()
    handle(element.id)
  }

  const { fonts } = useLocalFonts()

  const currentAlign = ALIGNMENTS.find(
    a => a.id === (element.textAlign || 'left'),
  )

  const fontOptions = React.useMemo(() => {
    return fonts.map(f => ({
      value: f.value,
      label: (
        <span
          style={{
            fontFamily: f.value,
            fontSize: '14px',
            lineHeight: '24px',
          }}
        >
          {f.label}
        </span>
      ),
      searchValue: f.label,
    }))
  }, [fonts])

  return (
    <div
      className='domino-toolbar h-[38px] absolute pointer-events-none z-[10]'
      style={{
        left: x * vs + vx,
        top: y * vs + vy,
        width: width * vs,
        height: (element.height || 0) * vs,
        transform: `rotate(${rotation}deg)`,
      }}
    >
      <div
        ref={containerRef}
        className={cn(
          'absolute left-1/2 flex items-center gap-[4px] bg-popover/90 backdrop-blur-md border border-border shadow-xl rounded-full px-[4px] pointer-events-auto whitespace-nowrap h-[38px]',
          readOnly && 'hidden',
        )}
        style={{
          bottom: '100%',
          marginBottom: '12px',
          transform: 'translate(-50%, 0)',
        }}
      >
        {/* Color Picker Native */}
        <div className='pl-4px pr-4px py-[4px] relative flex items-center justify-center'>
          <input
            type='color'
            value={element.color || '#000000'}
            onChange={e => handleUpdate({ color: e.target.value })}
            className='absolute opacity-0 inset-0 w-full h-full cursor-pointer'
          />
          <div
            className='w-[20px] h-[20px] rounded-full cursor-pointer border border-black/5 pointer-events-none'
            style={{ backgroundColor: element.color || '#000000' }}
          />
        </div>

        <div className='w-[1px] h-[16px] bg-border/60 flex-shrink-0' />

        {/* Font Family Select (using DropdownMenu) */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <div className='flex items-center gap-[4px] px-[8px] h-[28px] rounded-[14px] cursor-pointer hover:bg-accent transition-colors flex-shrink-0 min-w-[80px]'>
              <span className='text-[14px] truncate max-w-[80px]'>
                {fonts.find(f => f.value === element.fontFamily)?.label ||
                  '黑体'}
              </span>
              <Icon
                icon='dropdown'
                className='text-foreground/40 ml-auto'
                size='w-[16px] h-[16px] '
              />
            </div>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            side='bottom'
            align='start'
            className='max-h-[300px] min-w-[100px]'
          >
            {fontOptions.map(opt => (
              <DropdownMenuItem
                key={opt.value}
                onClick={() => handleUpdate({ fontFamily: opt.value })}
                className='focus:bg-accent data-[highlighted]:bg-accent cursor-pointer'
              >
                <div className='flex items-center px-[4px] w-full'>
                  {opt.label}
                </div>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Font Size - DropdownMenu and input */}
        <DropdownMenu>
          <div className='flex items-center gap-[2px] h-[28px] rounded-[14px] hover:bg-accent transition-colors flex-shrink-0 focus-within:bg-accent'>
            <input
              type='number'
              value={element.fontSize || 14}
              min={1}
              max={999}
              className='w-[40px] bg-transparent border-none text-right outline-none text-[14px] text-foreground tabular-nums [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
              onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
                if (e.key === 'Enter') e.currentTarget.blur()
              }}
              onChange={e => {
                const value = parseInt(e.target.value)
                if (!isNaN(value)) {
                  handleUpdate({ fontSize: value })
                }
              }}
            />
            <span className='text-[14px] text-foreground leading-none pb-[3px] pr-2px'>
              px
            </span>
            <DropdownMenuTrigger asChild>
              <div className='pr-4px h-[28px] flex items-center cursor-pointer'>
                <LocalIcon
                  name='dropdown'
                  className='w-[16px] h-[16px] text-foreground/40'
                />
              </div>
            </DropdownMenuTrigger>
          </div>
          <DropdownMenuContent
            side='bottom'
            align='end'
            className='max-h-[300px] min-w-[80px] tabular-nums'
          >
            {FONT_SIZES.map(s => (
              <DropdownMenuItem
                key={s}
                onClick={() => handleUpdate({ fontSize: s })}
                className='focus:bg-accent data-[highlighted]:bg-accent cursor-pointer'
              >
                <div className='flex items-center px-[4px] py-[2px] text-[14px] text-foreground'>
                  {s}px
                </div>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        <div className='w-[1px] h-[16px] bg-border/60 flex-shrink-0' />

        {/* Bold */}
        <div
          className={cn(
            'flex items-center justify-center w-[28px] h-[28px] rounded-[14px] cursor-pointer transition-colors flex-shrink-0',
            element.fontWeight === 'bold' || element.fontWeight === 700
              ? 'bg-muted text-foreground'
              : 'text-foreground hover:bg-accent',
          )}
          onClick={() =>
            handleUpdate({
              fontWeight:
                element.fontWeight === 'bold' || element.fontWeight === 700
                  ? 'normal'
                  : 'bold',
            })
          }
        >
          <LocalIcon name='bold' className='w-[16px] h-[16px]' />
        </div>

        {/* Italic */}
        <div
          className={cn(
            'flex items-center justify-center w-[28px] h-[28px] rounded-[14px] cursor-pointer transition-colors flex-shrink-0',
            element.fontStyle === 'italic'
              ? 'bg-muted text-foreground'
              : 'text-foreground hover:bg-accent',
          )}
          onClick={() =>
            handleUpdate({
              fontStyle: element.fontStyle === 'italic' ? 'normal' : 'italic',
            })
          }
        >
          <LocalIcon name='italic' className='w-[16px] h-[16px]' />
        </div>

        {/* Alignment Dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <div className='flex items-center gap-[4px] pl-8px h-[28px] rounded-[14px] cursor-pointer hover:bg-accent transition-colors flex-shrink-0'>
              {currentAlign?.icon()}
              <LocalIcon
                name='dropdown'
                className='w-[16px] h-[16px] text-foreground/40'
              />
            </div>
          </DropdownMenuTrigger>
          <DropdownMenuContent side='bottom' align='end'>
            {ALIGNMENTS.map(a => (
              <DropdownMenuItem
                key={a.id}
                onClick={() => handleUpdate({ textAlign: a.id as 'left' })}
                className='focus:bg-accent data-[highlighted]:bg-accent cursor-pointer'
              >
                <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
                  {a.icon()}
                  <span className='text-[14px] text-foreground whitespace-nowrap'>
                    {a.label}
                  </span>
                </div>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        {/* More Dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <div
              className={cn(
                'flex items-center justify-center w-[28px] h-[28px] rounded-[14px] cursor-pointer transition-colors flex-shrink-0',
                'text-foreground hover:bg-accent',
              )}
            >
              <LocalIcon
                name='image-editor-text-more'
                className='w-[16px] h-[16px]'
              />
            </div>
          </DropdownMenuTrigger>
          <DropdownMenuContent side='bottom' align='end'>
            {LAYER.map(a => (
              <DropdownMenuItem
                key={a.id}
                onClick={() => handleUpdateLayer(a.id)}
                className='focus:bg-accent data-[highlighted]:bg-accent cursor-pointer'
              >
                <div className='flex items-center gap-[8px] px-[4px] py-[2px]'>
                  {a.icon()}
                  <span className='text-[14px] text-foreground whitespace-nowrap'>
                    {a.label}
                  </span>
                </div>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  )
}
