import { mergeProps } from "@/utils/get-default-props";
import clsx from "clsx";
import { useState } from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import { TIcon } from "../Icon";
import { CopyProps } from "./PropsType";

const defaultProps = {
  type: "default",
  iconFontSize: "16px",
  animate: true,
};

export default function Copy(p: CopyProps) {
  const props = mergeProps(p, defaultProps);
  const {
    text,
    type,
    btnText,
    iconFontSize,
    className,
    animate,
    onCopy: onCustomCopy,
    ...restProps
  } = props;

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

  const onCopy = (ttext: string, result: boolean) => {
    if (result) {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    }
    onCustomCopy?.(ttext, result);
  };

  const baseStyles = "flex-none items-center justify-center uikit-border-none";
  const spaceStyles = {
    "space-x-[7px]": btnText,
  };
  const boxStyles = {
    "uikit-size-13 uikit-rounded-lg uikit-border uikit-border-l1 uikit-bg-bg5 uikit-text-red":
      type == "icon",
    "uikit-flex uikit-text-t1 uikit-h-13 uikit-min-w-13 uikit-rounded-lg uikit-border uikit-border-t1 uikit-text-base uikit-font-medium":
      type == "button",
    "uikit-text-t1 uikit-leading-none uikit-inline-flex": type == "default",
  };

  return (
    <CopyToClipboard
      text={text || ""}
      onCopy={onCopy}
      options={{ format: "text/plain" }}
    >
      <button
        {...restProps}
        className={clsx(baseStyles, spaceStyles, boxStyles, className)}
      >
        {animate && copied ? (
          <TIcon
            name="tg_wallet_finalize-facetiousness"
            className="uikit-text-green"
            fontSize={iconFontSize}
          />
        ) : (
          <TIcon name="tg_wallet_copy" fontSize={iconFontSize} />
        )}
        <span>{btnText}</span>
      </button>
    </CopyToClipboard>
  );
}
