"use client";

import * as React from "react";
import { Check, Copy } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { affiliatesTexts } from "@/lib/i18n/affiliates";

const texts = affiliatesTexts.api;

export function CodeBlock({
  code,
  label,
  tone = "neutral",
  className,
}: {
  code: string;
  label?: string;
  tone?: "neutral" | "request" | "response";
  className?: string;
}) {
  const [copied, setCopied] = React.useState(false);
  const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  React.useEffect(
    () => () => {
      if (timer.current) clearTimeout(timer.current);
    },
    [],
  );

  async function copy() {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      toast.success(texts.codeCopied);
      if (timer.current) clearTimeout(timer.current);
      timer.current = setTimeout(() => setCopied(false), 1800);
    } catch {
      toast.error(affiliatesTexts.copyFailed);
    }
  }

  return (
    <div
      className={cn(
        "overflow-hidden rounded-2xl border bg-slate-950 text-slate-100 shadow-sm dark:bg-[#080d1a]",
        className,
      )}
    >
      <div className="flex items-center justify-between gap-3 border-b border-white/10 px-4 py-2">
        <div className="flex items-center gap-2 min-w-0">
          <span
            className={cn(
              "size-1.5 shrink-0 rounded-full",
              tone === "request"
                ? "bg-blue-400"
                : tone === "response"
                  ? "bg-emerald-400"
                  : "bg-slate-500",
            )}
          />
          <span className="truncate font-mono text-[11px] tracking-wider text-white/50 uppercase">
            {label ?? "code"}
          </span>
        </div>
        <button
          type="button"
          onClick={copy}
          className="inline-flex shrink-0 items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium text-white/60 transition-colors hover:bg-white/10 hover:text-white"
          aria-label={texts.copyCode}
        >
          {copied ? (
            <Check className="size-3.5 text-emerald-400" />
          ) : (
            <Copy className="size-3.5" />
          )}
          {texts.copyCode}
        </button>
      </div>
      <div className="overflow-x-auto">
        <pre className="px-4 py-3.5 font-mono text-[12.5px] leading-relaxed whitespace-pre">
          <code>{code}</code>
        </pre>
      </div>
    </div>
  );
}

export default CodeBlock;
