import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import { Copy, Trash2 } from 'lucide-react'

import { HTMLEditor } from '../../../lib'
import { ColorPicker } from '@/components/base/color-picker'
import { rgbToHex } from '../hooks/useElementStyles'
import { loca } from '../loco'

interface BockToolbarProps {
  editor: HTMLEditor
  element: HTMLElement
}

const EditorColorPicker: React.FC<{
  editor: HTMLEditor
  element: HTMLElement
}> = ({ editor, element }) => {
  const computedStyle = window.getComputedStyle(element);
  const currentEleColor = computedStyle.background;
  const [color, setColor] = useState<string>(currentEleColor)
  
  useEffect(() => {
    setColor(currentEleColor)
  }, [currentEleColor])
  
  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={{
            background: 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.styleManager?.changeBackground(element, newColor);
            }} 
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

export const BlockToolbar: React.FC<BockToolbarProps> = ({
  editor,
  element,
}) => {
  const toolbarRef = useRef<HTMLDivElement | null>(null)
  const styleManager = editor.styleManager
  if (!editor || !element || !styleManager) return null

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actions = useMemo(
    () => [
      {
        key: 'color-picker',
        label: '',
        icon: EditorColorPicker,
        tooltip: loca.changeBgColor.content,
      },
      {
        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
      },
    ],
    [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 => {
          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?.()
              }}
            >
              <div className={`flex items-center ${a.label ? 'gap-[2px]' : ''}`}>
                <div>
                  {IconComp && (
                    a.key === 'color-picker' ? (
                      <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>
              <TooltipContent side="bottom">
                <p>{a.tooltip}</p>
              </TooltipContent>
            </Tooltip>
          )
        })}
      </div>
    </TooltipProvider>
  )
}
