import { CircularProgress, IconButton, IconButtonProps, Tooltip } from "@mui/material"
import { useState } from "react"

export type CustomIconApi = {
  setWorking: (isWorking: boolean) => void
}

export function CustomIcon({
  tooltip: tooptip,
  icon,
  color,
  handler,
}: {
  tooltip?: string
  icon: React.ReactNode
  color?: IconButtonProps["color"]
  handler?: (api: CustomIconApi) => void
}) {
  const [isWorking, setIsWorking] = useState(false)
  const api: CustomIconApi = {
    setWorking: setIsWorking,
  }

  const clickHandler = () => {
    if (handler && !isWorking) {
      handler(api)
    }
  }

  const iconButton = (
    <IconButton color={color || "primary"} onClick={clickHandler}>
      {isWorking ? <CircularProgress size={24} /> : icon}
    </IconButton>
  )

  const result = tooptip ? <Tooltip title={tooptip}>{iconButton}</Tooltip> : iconButton

  return result
}
