import * as React from "react";
import IconButton, { IconButtonProps } from "@mui/material/IconButton";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import CheckIcon from "@mui/icons-material/Check";
import Button, { ButtonProps } from "@mui/material/Button";

export interface CopyIconButtonProps extends IconButtonProps {
  content: string;
}

export interface CopySquareIconButtonProps extends ButtonProps {
  content: string;
}

export default function CopyIconButton(props: CopyIconButtonProps) {
  const { content, ...others } = props;

  const [copied, setCopied] = React.useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(content);
    setCopied(true);
    setTimeout(() => {
      setCopied(false);
    }, 1000);
  };

  return (
    <>
      <IconButton
        size="small"
        aria-label="copy"
        onClick={handleCopy}
        disabled={copied}
        {...others}
      >
        {!copied && <ContentCopyIcon fontSize="inherit" />}
        {copied && <CheckIcon fontSize="inherit" />}
      </IconButton>
    </>
  );
}

export function CopySquareIconButton(props: CopySquareIconButtonProps) {
  const { content, sx, ...others } = props;

  const [copied, setCopied] = React.useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(content);
    setCopied(true);
    setTimeout(() => {
      setCopied(false);
    }, 1000);
  };

  return (
    <>
      <Button
        variant="outlined"
        aria-label="copy"
        onClick={handleCopy}
        disabled={copied}
        startIcon={
          copied ? (
            <CheckIcon fontSize="inherit" />
          ) : (
            <ContentCopyIcon fontSize="inherit" />
          )
        }
        sx={{
          backgroundColor: "#F6F8FC",
          color: "#909eaa",
          borderColor: "#909eaa",
          minWidth: "unset",
          padding: "6px",
          width: "fit-content",
          "& .MuiButton-startIcon": {
            margin: 0,
          },
          "&:hover": {
            backgroundColor: "#F6F8FC",
            borderColor: "#909eaa",
          },
          ...sx,
        }}
        {...others}
      ></Button>
    </>
  );
}
