import type {ButtonProps} from "@heroui/react";

import {useClipboard} from "@heroui/use-clipboard";
import {memo} from "react";
import {Tooltip} from "@heroui/react";

import {PreviewButton} from "./preview-button";

import {CheckLinearIcon, CopyLinearIcon} from "@/components/icons";

export interface CopyButtonProps extends ButtonProps {
  value?: string;
}

export const CopyButton = memo<CopyButtonProps>(({value, className, ...buttonProps}) => {
  const {copy, copied} = useClipboard();

  const icon = copied ? (
    <CheckLinearIcon
      className="opacity-0 scale-50 data-[visible=true]:opacity-100 data-[visible=true]:scale-100 transition-transform-opacity"
      data-visible={copied}
      size={16}
    />
  ) : (
    <CopyLinearIcon
      className="opacity-0 scale-50 data-[visible=true]:opacity-100 data-[visible=true]:scale-100 transition-transform-opacity"
      data-visible={!copied}
      size={16}
    />
  );

  const handleCopy = () => {
    copy(value);
  };

  return (
    <Tooltip
      key={copied ? "copied" : "copy"}
      className="text-xs px-2"
      closeDelay={0}
      content={copied ? "Copied!" : "Copy"}
      radius="md"
    >
      <PreviewButton className={className} icon={icon} onPress={handleCopy} {...buttonProps} />
    </Tooltip>
  );
});

CopyButton.displayName = "CopyButton";
