import React from "react";
import PropTypes from "prop-types";
import { Button, Tooltip, message } from "antd";
import CopyIcon from "../icons/CopyIcon";

const CopyButton = ({
  text,
  tooltip = "Copy",
  size = "small",
  type = "text",
}) => {
  const [messageApi, contextHolder] = message.useMessage();

  const doCopy = (copyText) => {
    if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(copyText)
        .then(() => {
          messageApi.success("Copied to clipboard");
        })
        .catch(() => {
          messageApi.error("Failed to copy");
        });
    } else if (
      document.queryCommandSupported &&
      document.queryCommandSupported("copy")
    ) {
      // Legacy fallback
      const textarea = document.createElement("textarea");
      textarea.value = copyText;
      textarea.setAttribute("readonly", "");
      textarea.style.position = "absolute";
      textarea.style.left = "-9999px";
      document.body.appendChild(textarea);
      textarea.select();
      try {
        document.execCommand("copy");
        messageApi.success("Copied to clipboard");
      } catch (err) {
        messageApi.error("Failed to copy");
      }
      document.body.removeChild(textarea);
    } else {
      messageApi.error("Copy not supported in this browser");
    }
  };

  return (
    <>
      {contextHolder}
      <Tooltip title={tooltip} arrow={false}>
        <Button
          icon={<CopyIcon />}
          style={{ minWidth: 25 }}
          width={20}
          size={size}
          type={type}
          onClick={() => doCopy(text)}
        />
      </Tooltip>
    </>
  );
};

CopyButton.propTypes = {
  text: PropTypes.string.isRequired,
  style: PropTypes.object,
  tooltip: PropTypes.string,
  size: PropTypes.string,
  type: PropTypes.string,
};

export default CopyButton;
