import { Chip, Tooltip } from "@mui/material";
import { useAlert } from "../hooks/contexts_provider/AlertDialogProvider";
import { useSnackbar } from "../hooks/contexts_provider/SnackbarProvider";

export function CopyTextChip(p: { text: string }): React.ReactElement {
  const snackbar = useSnackbar();
  const alert = useAlert();

  const copyTextToClipboard = () => {
    try {
      navigator.clipboard.writeText(p.text);
      snackbar(`'${p.text}' was copied to clipboard.`);
    } catch (e) {
      console.error(`Failed to copy text to the clipboard! ${e}`);
      alert(p.text);
    }
  };

  return (
    <Tooltip title="Copy to clipboard">
      <Chip
        label={p.text}
        variant="outlined"
        style={{ margin: "5px" }}
        onClick={copyTextToClipboard}
      />
    </Tooltip>
  );
}
