import { Check, Copy } from "lucide-react";
import * as React from "react";
import { cn } from "../../lib/utils";
import { Button, type ButtonProps } from "./button";

interface CopyButtonProps extends ButtonProps {
  value: string;
  onCopy?: () => void;
}

export function CopyButton({
  value,
  onCopy,
  className,
  variant = "secondary",
  size = "icon",
  ...props
}: CopyButtonProps) {
  const [hasCopied, setHasCopied] = React.useState(false);

  React.useEffect(() => {
    if (hasCopied) {
      const timer = setTimeout(() => setHasCopied(false), 1500);
      return () => clearTimeout(timer);
    }
  }, [hasCopied]);

  const copyToClipboard = async () => {
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(value);
      } else {
        // Fallback for non-secure contexts (HTTP) or missing navigator.clipboard
        const textArea = document.createElement("textarea");
        textArea.value = value;
        textArea.style.position = "fixed";
        textArea.style.left = "-9999px";
        textArea.style.top = "0";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
          const successful = document.execCommand("copy");
          if (!successful) throw new Error("execCommand copy failed");
        } catch (err) {
          console.error("Fallback: Oops, unable to copy", err);
          throw err;
        } finally {
          document.body.removeChild(textArea);
        }
      }
      setHasCopied(true);
      if (onCopy) onCopy();
    } catch (err) {
      console.error("Failed to copy text: ", err);
    }
  };

  return (
    <Button
      size={size}
      variant={variant}
      className={cn("relative z-10", className)}
      onClick={copyToClipboard}
      {...props}
    >
      <span className="sr-only">Copy</span>
      {hasCopied ? (
        <Check className="h-4 w-4 text-emerald-500 transition-all scale-110" />
      ) : (
        <Copy className="h-4 w-4 transition-all" />
      )}
    </Button>
  );
}
