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 { rgbToHex } from '../../toolbar-web/hooks/useElementStyles'
import {
  ChevronDown,
  Bold,
  Underline,
  Italic,
  AlignLeft,
  AlignCenter,
  AlignRight,
} from 'lucide-react'

import type { HTMLEditor } from '../../../lib'
import { loca } from './loco'
import { ColorPicker } from '@/components/base/color-picker'
import { type SelectionFormatting } from '../hooks/useSelectionFormatting'

interface TextToolbarProps {
  editor: HTMLEditor
  formatState: SelectionFormatting
}

const biMap = new Map<number | string, number | string>([
  ['h1', 60], ['h2', 40], ['h3', 32],
  ['h4', 24], ['h5', 18], ['h6', 14],
  [60, 'h1'], [40, 'h2'], [32, 'h3'],
  [24, 'h4'], [18, 'h5'], [14, 'h6'],
  ['p', 14], [14, 'p']
]);

const TextLevelChangger: React.FC<{
  editor: HTMLEditor
  formatState: SelectionFormatting
}> = ({ editor, formatState }) => {
  const [selectedKey, setSelectedKey] = useState<
    'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p'
  >(biMap.get(parseInt(formatState.fontSize || '0')) || 'p' as any)

  useEffect(() => {
    const key = biMap.get(parseInt(formatState.fontSize || '0'))
    setSelectedKey(key || 'p' as any);
  }, [formatState])

  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: 'p', label: loca.normal.content },
  ]

  const labelMap: Record<string, string> = {
    h1: 'H1',
    h2: 'H2',
    h3: 'H3',
    h4: 'H4',
    h5: 'H5',
    h6: 'H6',
    p: loca.normal.content,
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <span
          className='flex items-center justify-between gap-[4px] pl-[8px] pr-[4px] cursor-pointer'
        >
          <span>{labelMap[selectedKey]}</span>
          <span>
            <ChevronDown className='w-3 h-3' />
          </span>
        </span>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        className='html-editor-heading-dropdown min-w-[204px]'
        align='start'
      >
        <DropdownMenuRadioGroup
          value={selectedKey}
          onValueChange={(value) => {
            setSelectedKey(value as any)
            if (editor) {
              editor.globalEditable?.applySelectionFontSize(biMap.get(value) + 'px')
            }
          }}
        >
          {menuItems.map((item) => (
            <DropdownMenuRadioItem key={item.key} value={item.key}>
              {item.label}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

const EditorColorPicker: React.FC<{
  editor: HTMLEditor
  formatState: SelectionFormatting
}> = ({ editor, formatState }) => {
  const [color, setColor] = useState<string>(formatState.color || '#000000')

  useEffect(() => {
    if (formatState.color) {
      setColor(formatState.color)
    }
  }, [formatState.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: color,
              }}
            >
              <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={rgbToHex(color)}
            onChange={(newColor) => {
              setColor(newColor)
              editor.globalEditable?.applySelectionColor(newColor)
            }}
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

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

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

  const handleToggleBold = () => {
    editor.globalEditable?.applySelectionBold()
  }

  const handleToggleItalic = () => {
    editor.globalEditable?.applySelectionItalic()
  }

  const handleToggleUnderline = () => {
    editor.globalEditable?.applySelectionUnderline()
  }

  const handleTextAlign = (align: 'left' | 'center' | 'right') => {
    editor.globalEditable?.applySelectionAlign(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',
      },
    ],
    [
      handleToggleBold,
      handleToggleItalic,
      handleToggleUnderline,
      handleTextAlign,
      textAlign,
      isBold,
      isItalic,
      isUnderline,
      editor,
    ],
  )

  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 => {
          if (a.key === 'split-line') {
            return (
              <div key={a.key} className='h-[50%] w-[1px] bg-border'></div>
            )
          }

          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?.()
              }}
            >
              <div
                className={`flex items-center ${a.label ? 'gap-[2px]' : ''}`}
              >
                <div>
                  {a.icon && (
                    <a.icon
                      editor={editor}
                      formatState={formatState}
                      className={`w-4 h-4 ${a.key === 'delete' ? 'text-destructive' : 'text-foreground'}`}
                    />
                  )}
                </div>
                <div>{a.label}</div>
              </div>
            </div>
          )

          if (a.tooltip) {
            return (
              <Tooltip key={a.key}>
                <TooltipTrigger asChild>
                  {content}
                </TooltipTrigger>
                <TooltipContent side='bottom'>
                  <p>{a.tooltip}</p>
                </TooltipContent>
              </Tooltip>
            )
          }

          return <React.Fragment key={a.key}>{content}</React.Fragment>
        })}
      </div>
    </TooltipProvider>
  )
}
