import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import {
  ChevronDown,
  Bold,
  Underline,
  Italic,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Copy,
  Trash2,
} from 'lucide-react'

import type { HTMLEditor } from '../../../lib'
import {
  useFontSize,
  useTextColor,
  useFontWeight,
  useFontStyle,
  useTextDecoration,
  useTextAlign,
} from '../hooks/useElementStyles'
import { ColorPicker } from '@/components/base/color-picker'
import { loca } from '../loco'

interface TextToolbarProps {
  editor: HTMLEditor
  element: HTMLElement
}

const TextLevelChangger: React.FC<{
  editor: HTMLEditor
  element: HTMLElement
}> = ({ editor, element }) => {
  const [fontSize] = useFontSize(element)
  const [selectedKey, setSelectedKey] = useState<
    'H1' | 'H2' | 'H3' | 'H4' | 'H5' | 'H6' | 'doc' | 'ol' | 'ul'
  >('doc')
  
  const menuItems = [
    { key: 'H1', label: 'H1' },
    { key: 'H2', label: 'H2' },
    { key: 'H3', label: 'H3' },
    { key: 'H4', label: 'H4' },
    { key: 'H5', label: 'H5' },
    { key: 'H6', label: 'H6' },
    { key: 'doc', label: '正文' },
  ]
  const tagName = element.tagName.toLowerCase()

  const activeMap = {
    H1: { isActive: fontSize === 60, label: 'H1', key: 'H1' },
    H2: { isActive: fontSize === 40, label: 'H2', key: 'H2' },
    H3: { isActive: fontSize === 32, label: 'H3', key: 'H3' },
    H4: { isActive: fontSize === 24, label: 'H4', key: 'H4' },
    H5: { isActive: fontSize === 18, label: 'H5', key: 'H5' },
    H6: { isActive: fontSize === 14, label: 'H6', key: 'H6' },
    doc: {
      isActive: (tagName === 'p' || tagName === 'span') && fontSize === 18,
      label: '正文',
      key: 'doc',
    },
  }
  const defaultSelectedItem = Object.values(activeMap).find(i => i.isActive)

  console.log('defaultSelectedItem:',defaultSelectedItem)
  const textTypes: { [key: string]: string } = {
    doc: '18px',
    H1: '60px',
    H2: '40px',
    H3: '32px',
    H4: '24px',
    H5: '18px',
    H6: '14px',
  }

  useEffect(() => {
    if (!defaultSelectedItem) {
      setSelectedKey('doc')
      return
    }
    setSelectedKey(defaultSelectedItem.key as any)
  }, [defaultSelectedItem?.key])

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <span className='flex html-editor-heading-dropdown items-center justify-between gap-[4px] pl-[8px] pr-[4px] cursor-pointer'>
          <span>{activeMap[selectedKey as keyof typeof activeMap]?.label}</span>
          <ChevronDown className="w-3 h-3" />
        </span>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="min-w-[204px]">
        <DropdownMenuRadioGroup 
          value={selectedKey} 
          onValueChange={(value) => {
            setSelectedKey(value as any)
            const newSize = textTypes[value]
            if (editor) {
              editor.styleManager?.changeFontSize(element, newSize)
            }
          }}
        >
          {menuItems.map(item => (
            <DropdownMenuRadioItem key={item.key} value={item.key}>
              {item.label}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

const EditorColorPicker: React.FC<{
  editor: HTMLEditor
  element: HTMLElement
}> = ({ editor, element }) => {
  const [color, setColor] = useTextColor(element)
  const bgColor = useMemo<string>(
    () => (typeof color === 'string' ? color : (color as any)?.toHexString?.() || '#000000'),
    [color],
  )

  return (
    <div className='editor-toolbar-color-picker w-[16px] h-[16px]'>
      <Popover>
        <PopoverTrigger asChild>
          <div 
            data-html-editor-ui="true"
            className='flex flex-row items-center justify-center w-[16px] h-[16px] rounded-[16px] bg-[#eee] cursor-pointer'
          >
            <div
              className='w-[14px] h-[14px] rounded-[14px] overflow-hidden'
              style={{ backgroundColor: bgColor }}
            >
              <div
                className='w-full h-full'
                style={{
                  backgroundSize: '8px 8px',
                  backgroundImage:
                    'conic-gradient(rgba(98, 105, 153, 0.1) 25%, transparent 25% 50%, rgba(98, 105, 153, 0.1) 50% 75%, transparent 75% 100%)',
                }}
              ></div>
            </div>
          </div>
        </PopoverTrigger>
        <PopoverContent 
          className='w-auto p-3'
          onMouseDown={(e) => e.stopPropagation()}
          onClick={(e) => e.stopPropagation()}
        >
          <ColorPicker
            color={bgColor.startsWith('#') ? bgColor : '#000000'}
            onChange={(newColor) => {
              setColor(newColor)
              editor.styleManager?.changeColor(element, newColor)
            }}
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

export const TextToolbar: React.FC<TextToolbarProps> = ({
  editor,
  element,
}) => {
  const isBold = useFontWeight(element)
  const isItalic = useFontStyle(element)
  const isUnderline = useTextDecoration(element)
  const textAlign = useTextAlign(element)
  const toolbarRef = useRef<HTMLDivElement | null>(null)

  const styleManager = editor.styleManager
  if (!editor || !element || !styleManager) return null

  const handleToggleBold = () => {
    styleManager.changeFontWeight(element, isBold ? 'normal' : 'bold')
  }

  const handleToggleItalic = () => {
    styleManager.changeFontStyle(element, isItalic ? 'normal' : 'italic')
  }

  const handleToggleUnderline = () => {
    styleManager.changeTextDecoration(element, isUnderline ? 'none' : 'underline')
  }

  const handleTextAlign = (align: string) => {
    styleManager.changeTextAlign(element, align)
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actions = useMemo(
    () => [
      {
        key: 'tools',
        label: '',
        icon: TextLevelChangger,
      },
      {
        key: 'color-picker',
        label: '',
        icon: EditorColorPicker,
        tooltip: loca.changeTextColor.content,
      },
      {
        key: 'bold',
        label: '',
        icon: Bold,
        tooltip: loca.textBlod.content,
        run: handleToggleBold,
        isActive: isBold,
      },
      {
        key: 'italic',
        label: '',
        icon: Italic,
        tooltip: loca.textItalic.content,
        run: handleToggleItalic,
        isActive: isItalic,
      },
      {
        key: 'underline',
        label: '',
        icon: Underline,
        tooltip: loca.textUnderline.content,
        run: handleToggleUnderline,
        isActive: isUnderline,
      },
      {
        key: 'text-align-left',
        label: '',
        icon: AlignLeft,
        tooltip: loca.textAlignLeft.content,
        run: () => {
          handleTextAlign('left')
        },
        isActive: textAlign === 'left' || textAlign === 'start',
      },
      {
        key: 'text-align-center',
        label: '',
        icon: AlignCenter,
        tooltip: loca.textAlignCenter.content,
        run: () => {
          handleTextAlign('center')
        },
        isActive: textAlign === 'center',
      },
      {
        key: 'text-align-right',
        label: '',
        icon: AlignRight,
        tooltip: loca.textAlignRight.content,
        run: () => {
          handleTextAlign('right')
        },
        isActive: textAlign === 'right' || textAlign === 'end',
      },
      {
        key: 'split-line',
        label: '',
      },
      {
        key: 'duplicate',
        label: '',
        icon: Copy,
        tooltip: loca.copy.content,
        run: () => {
          editor.copyElement(element)
        },
        isActive: false,
      },
      {
        key: 'delete',
        label: '',
        icon: Trash2,
        tooltip: loca.delete.content,
        run: () => {
          editor.deleteElement(element)
        },
        isActive: false,
      },
    ],
    [
      handleToggleBold,
      handleToggleItalic,
      handleToggleUnderline,
      handleTextAlign,
      textAlign,
      isBold,
      isItalic,
      isUnderline,
      editor,
      element,
    ],
  )

  return (
    <TooltipProvider>
      <div
        ref={toolbarRef}
        className='html-editor-toolbar'
        style={{
          height: '36px',
          padding: '4px 8px',
          borderRadius: 100,
          zIndex: 10000,
          background: 'var(--editor-surface)',
          backdropFilter: 'blur(18px)',
          border: '0.5px solid var(--editor-border-strong)',
          boxShadow: '0 8px 24px var(--editor-shadow)',
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          gap: '2px',
          whiteSpace: 'nowrap',
        }}
      >
        {actions.map((a: any) => {
          if (a.key === 'split-line') {
            return (
              <div key={a.key} className='h-[50%] w-[1px] bg-border'></div>
            )
          }

          const IconComp = a.icon as any;
          const isDelete = a.key === 'delete';
          const iconClassName = `w-4 h-4 ${isDelete ? 'text-destructive' : 'text-foreground'}`;
          const content = (
            <div
              className={`
                min-w-[28px] min-h-[28px] flex flex-row items-center justify-center text-foreground hover:bg-accent cursor-pointer transition-all rounded-[28px] ${a.isActive ? 'bg-accent text-accent-foreground' : ''} ${a.label ? 'px-[8px]' : ''}
              `}
              onMouseDown={e => e.preventDefault()}
              onClick={() => {
                a.run && a.run()
              }}
            >
              <div
                className={`flex items-center ${a.label ? 'gap-[2px]' : ''}`}
              >
                <div>
                   {IconComp && (
                    ['tools', 'color-picker'].includes(a.key) ? (
                      <IconComp editor={editor} element={element} className={iconClassName} />
                    ) : (
                      <IconComp className={iconClassName} />
                    )
                  )}
                </div>
                <div>{a.label}</div>
              </div>
            </div>
          )

          return (
            <Tooltip key={a.key}>
              <TooltipTrigger asChild>
                {content}
              </TooltipTrigger>
              {a.tooltip ? <TooltipContent side="bottom">
                <p>{a.tooltip}</p>
              </TooltipContent> : null}
            </Tooltip>
          )
        })}
      </div>
    </TooltipProvider>
  )
}
