import { useState } from "react";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import CheckIcon from "@mui/icons-material/Check";
import IconButton, { IconButtonProps } from "@mui/material/IconButton";
import { Tooltip } from "@mui/material";
import { SxProps, Theme } from "@mui/material";

interface CopyBubbleProps extends IconButtonProps {
  content: string | undefined;
  sx?: SxProps<Theme>;
  tooltip?: string;
}

const CopyBubble = ({
  content,
  sx,
  tooltip = "Copy to clipboard",
  onClick,
  ...rest
}: CopyBubbleProps) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = (e: any) => {
    if (content === undefined) {
      return;
    }

    navigator.clipboard.writeText(content.trim()).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000); // Reset after 2 seconds
    });

    if (onClick) {
      onClick(e);
    }
  };

  return (
    <Tooltip title={tooltip} placement="top" arrow>
      <IconButton
        onClick={(e) => {
          handleCopy(e);
        }}
        sx={{
          width: 24,
          height: 24,
          opacity: 0.75,
          bgcolor: "background.paper",
          "&:hover": { bgcolor: "action.hover", opacity: 1 },
          ...sx,
        }}
        size="small"
        color={copied ? "success" : "default"}
        {...rest}
      >
        {copied ? (
          <CheckIcon sx={{ width: 16, height: 16 }} />
        ) : (
          <ContentCopyIcon sx={{ width: 16, height: 16 }} />
        )}
      </IconButton>
    </Tooltip>
  );
};

export { CopyBubble };
