import React, { useMemo, useRef } from 'react'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { Copy, Trash2, ImagePlus } from 'lucide-react'


import { HTMLEditor } from '../../../lib'
import { loca } from '../loco'
// import { customUpload } from '../utils/upload'

interface BockToolbarProps {
  editor: HTMLEditor
  element: HTMLElement
}


const EditorImageUpload: React.FC<{
  editor: HTMLEditor,
  element: HTMLElement
}> = ({ editor: _editor, element: _element }) => {
  const inputRef = useRef<HTMLInputElement>(null)

  const onFileChange: React.ChangeEventHandler<HTMLInputElement> = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      try{
        // const res = await customUpload({ file })
        // if (res) {
        //   editor.replaceImage(element, res.url)
        // }
      }catch{
        
      }
    }
  }
  
  return (
    <div className='w-[28px] h-[28px] relative flex flex-row items-center justify-center cursor-pointer'>
      <input type="file" accept='.jpeg,.jpg,.png,.gif,.bmp,.webp' multiple={false} ref={inputRef} className='absolute w-full h-full top-0 left-0 border-none outline-none cursor-pointer opacity-0 text-[0px]' onChange={onFileChange}/>
      <ImagePlus className="w-4 h-4" />
    </div>
  )
}

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

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actions = useMemo(
    () => [
      {
        key: 'image-replace',
        icon: EditorImageUpload,
        tooltip: loca.imageUpload.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 === 'image-replace' ? (
                      <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>
  )
}
