"use client";
import { useTranslations } from "next-intl";
import React, { useState } from "react";
import ShowAlertMixin from "./ShowAlertMixin";

const CopyToClipboard = ({
  text,
  children,
  className,
}: {
  text: string;
  children?: React.ReactNode;
  className?: string;
}) => {
  const [copySuccess, setCopySuccess] = useState("");
  const [isDisabled, setIsDisabled] = useState(false);
  const t = useTranslations("validations");

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopySuccess(t("copied"));
      setIsDisabled(true);
      ShowAlertMixin({
        icon: "success",
        title: t("copied"),
      });
      setTimeout(() => {
        setCopySuccess("");
        setIsDisabled(false);
      }, 2000);
    } catch (err) {
      setCopySuccess("Failed to copy!");
    }
  };

  return (
    <div>
      <button
        onClick={copyToClipboard}
        className={
          className
            ? className
            : "copy-button cursor-pointer  text-success px-4 py-2 rounded w-full"
        }
        disabled={isDisabled}
      >
        {children ? (
          children
        ) : (
          <>{copySuccess ? copySuccess : t("Copy the code")}</>
        )}
      </button>
    </div>
  );
};

export default CopyToClipboard;
