import { cn } from "@xtablo/shared";
import { Check, Copy } from "lucide-react";
import React from "react";
import { useCopyToClipboard } from "../hooks/use-clipboard";
import { Button, type ButtonProps } from "./button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";

export type ClipboardProps = {
  timeout?: number;
  children: (payload: { copied: boolean; copy: (value: string) => void }) => React.ReactNode;
};

export function Clipboard({ timeout, children }: ClipboardProps) {
  const { copied, copy } = useCopyToClipboard({ timeout });
  return children({ copied, copy }) as React.ReactElement;
}

export function CopyButton({
  copyValue,
  label = "Copy",
  labelAfterCopied = "Copied to clipboard",
  icon,
  variant = "ghost",
  children,
  className,
  ...props
}: {
  copyValue: string;
  label?: string;
  labelAfterCopied?: string;
  icon?: React.ReactElement<{ className?: string }>;
} & Omit<ButtonProps, "onClick">) {
  return (
    <Clipboard>
      {({ copied, copy }) => {
        return (
          <TooltipProvider delayDuration={0}>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant={variant}
                  size={!children ? "icon" : undefined}
                  aria-label={label}
                  className={className}
                  {...props}
                  onClick={() => copy(copyValue)}
                >
                  {children ?? (
                    <div className="relative flex items-center justify-center">
                      {icon ? (
                        React.cloneElement(icon, {
                          className: cn(
                            icon.props.className,
                            "transition-all w-4 h-4",
                            copied ? "absolute scale-0 opacity-0" : "scale-100 opacity-100"
                          ),
                        })
                      ) : (
                        <Copy
                          className={cn(
                            "transition-all w-4 h-4",
                            copied ? "absolute scale-0 opacity-0" : "scale-100 opacity-100"
                          )}
                        />
                      )}

                      <Check
                        className={cn(
                          "text-green-600 dark:text-green-400 transition-all w-4 h-4",
                          copied ? "scale-100 opacity-100" : "absolute scale-0 opacity-0"
                        )}
                      />
                    </div>
                  )}
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>{copied ? labelAfterCopied : label}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        );
      }}
    </Clipboard>
  );
}
