import React, { forwardRef } from 'react'
import type {
  ForwardedRef,
  DetailedHTMLProps,
  HTMLAttributes,
  ReactNode,
} from 'react'
import { cn } from '@/utils/cn'
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
} from './tooltip'
import { LocalIcon } from './local-icon'

export interface IconButtonProps
  extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
  disabled?: boolean
  disabledTip?: string
  className?: string
  icon?: string | ReactNode
  iconSize?: string
  size?: string
  onClick?: (event: React.MouseEvent<HTMLSpanElement>) => void

  children?: ReactNode
}

export const IconButton = forwardRef(function IconButton(
  props: IconButtonProps,
  ref: ForwardedRef<HTMLDivElement>,
) {
  const {
    disabled,
    disabledTip,
    className,
    icon,
    iconSize = 'w-[16px] h-[16px]',
    size = 'w-[24px] h-[24px]',
    onClick,
    children,
    ...rest
  } = props

  const content = (
    <div
      ref={ref}
      className={cn(
        'flex items-center justify-center rounded-[8px] duration-300',
        size,
        className,
        {
          'cursor-pointer text-[var(--editor-text)] hover:bg-accent': !disabled,
          'cursor-not-allowed opacity-40': disabled,
        },
      )}
      onClick={disabled ? undefined : onClick}
      {...rest}
    >
      {typeof icon === 'string' ? (
        <LocalIcon name={icon} className={iconSize} />
      ) : (
        <div className={iconSize}>{icon}</div>
      )}
      {children}
    </div>
  )

  if (!disabled || !disabledTip) {
    return content
  }

  return (
    <TooltipProvider delayDuration={200}>
      <Tooltip>
        <TooltipTrigger asChild>{content}</TooltipTrigger>
        <TooltipContent>{disabledTip}</TooltipContent>
      </Tooltip>
    </TooltipProvider>
  )
})

interface IconProps
  extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
  icon?: string
  size?: string
  className?: string
  onClick?: (event: React.MouseEvent<HTMLSpanElement>) => void
}

export const Icon = forwardRef(function Icon(
  props: IconProps,
  ref: ForwardedRef<HTMLDivElement>,
) {
  const { icon, size = 'w-[16px] h-[16px]', className, ...rest } = props

  return (
    <div
      ref={ref}
      data-icon={icon}
      className={cn('inline-flex items-center justify-center', size, className)}
      {...rest}
    >
      <LocalIcon name={icon || ''} className='size-full' />
    </div>
  )
})
