"use client";

import { useLocale, useLocaleFunction } from "@/hooks/use-localed";
import type { Locale } from "@/lib/locale";
import { cn } from "@/lib/utils";
import { CheckIcon, CopyIcon } from "lucide-react";
import {
  cloneElement,
  type ReactElement,
  type Ref,
  useRef,
  useState,
} from "react";

declare global {
  interface TidbaiWidget {
    open: boolean;

    newChat(message: string): void;
  }

  const tidbai: TidbaiWidget;
}

interface CopyToClipboardProps {
  children: ReactElement<{ ref: Ref<HTMLElement | null> }>;
  className?: string;
  timeout?: number;
  position?: "top-right" | "top-left" | "bottom-right" | "bottom-left";
  showCopy?: boolean;
}

const positionClasses = {
  "top-right": "right-2.5 top-2.5",
  "top-left": "left-2.5 top-2.5",
  "bottom-right": "right-2.5 bottom-2.5",
  "bottom-left": "left-2.5 bottom-2.5",
};

export function CopyToClipboard({
  children,
  className,
  timeout = 1000,
  position = "top-right",
  showCopy = true,
}: CopyToClipboardProps) {
  const [copied, setCopiedState] = useState(false);
  const ref = useRef<HTMLElement | null>(null);
  const locale = useLocale();

  const t = useLocaleFunction();

  const handleCopy = () => {
    if (copied) return;
    navigator.clipboard.writeText(
      (ref.current?.innerText ?? "").replace(/(\n\s*)*$/, "")
    );
    setCopiedState(true);
    setTimeout(() => {
      setCopiedState(false);
    }, timeout);
  };

  // Temporarily hide Explain on code blocks. Set to true to restore.
  const showExplain = false;

  return (
    <>
      {showExplain && (
        <button
          className={cn(
            "absolute border rounded-md z-0 text-foreground transition-all opacity-70 bg-card/70 group-hover:opacity-100 hover:bg-card select-none cursor-pointer",
            positionClasses[position],
            className,
            showCopy && "right-10"
          )}
          onClick={() => {
            tidbai.open = true;
            setTimeout(() => {
              tidbai.newChat(
                `${message[locale]}\n${ref.current?.innerText ?? ""}`
              );
            }, 200);
          }}
        >
          <span className="inline-flex items-center text-xs px-1.5">
            {t("common.explain-with-ai")}
          </span>
        </button>
      )}
      {showCopy && (
        <button
          className={cn(
            "absolute p-1 border rounded-md z-0 text-foreground transition-all opacity-70 bg-card/70 group-hover:opacity-100 hover:bg-card select-none cursor-pointer",
            positionClasses[position],
            className
          )}
          onClick={handleCopy}
        >
          {copied ? (
            <CheckIcon className="size-3" />
          ) : (
            <CopyIcon className="size-3" />
          )}
        </button>
      )}
      {cloneElement(children, { ref })}
    </>
  );
}

const message: Record<Locale, string> = {
  zh: "Explain this command(please answer with simplified Chinese)",
  ja: "Explain this command(please answer with Japanese)",
  en: "Explain this command(please answer with English)",
  ko: "Explain this command(please answer with Korean)",
};
