"use client"
import React, { ElementRef, forwardRef, useState } from "react"
import { useDebounceCallback } from "usehooks-ts"
import { Tooltip } from "../Tooltip"
import { UnstyledButton, UnstyledButtonProps } from "../UnstyledButton"

export type CopyToClipboardProps = {
  children: React.ReactNode
  text: string
  tooltipText?: string
  tooltipOnCopiedText?: string
  className?: string
} & UnstyledButtonProps

export const CopyToClipboard = forwardRef<
  ElementRef<typeof UnstyledButton>,
  CopyToClipboardProps
>(function CopyToClipboard(
  {
    children,
    onClick,
    className,
    text,
    tooltipText,
    tooltipOnCopiedText,
    ...rest
  },
  ref,
) {
  const [open, setOpen] = useState(false)

  const [hasCopied, setHasCopied] = useState(false)

  const debouncedHasCopied = useDebounceCallback(setHasCopied, 3_000)

  const beforeCopiedText = tooltipText ?? "Copy"
  const afterCopiedText = tooltipOnCopiedText ?? "Copied!"

  return (
    <Tooltip
      content={hasCopied ? afterCopiedText : beforeCopiedText}
      hoverable={false}
      open={hasCopied ? true : open}
      onOpenChange={open => {
        if (hasCopied && !open) {
          setHasCopied(false)
        }

        setOpen(open)
      }}
    >
      <UnstyledButton
        className={className}
        ref={ref}
        onClick={e => {
          navigator.clipboard.writeText(text)
          debouncedHasCopied.cancel()
          setHasCopied(true)
          debouncedHasCopied(false)
          onClick?.(e)
        }}
        {...rest}
      >
        {children}
      </UnstyledButton>
    </Tooltip>
  )
})
