"use client";

import { useState } from "react";
import { cn } from "@/lib/utils";

interface CodeBlockProps {
  code: string;
  language?: string;
  title?: string;
  className?: string;
}

export function CodeBlock({ code, language, title, className }: CodeBlockProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className={cn("group relative rounded-lg border border-white/10 bg-white/[0.03] overflow-hidden", className)}>
      {(title || language) && (
        <div className="flex items-center justify-between border-b border-white/[0.06] px-4 py-2">
          <span className="text-xs font-medium text-gray-400">
            {title ?? language}
          </span>
          <button
            onClick={handleCopy}
            className={cn(
              "rounded px-2.5 py-1 text-xs font-medium transition-all",
              copied
                ? "bg-emerald-600/20 text-emerald-400"
                : "bg-white/[0.06] text-gray-500 hover:bg-white/10 hover:text-gray-300 opacity-0 group-hover:opacity-100",
            )}
          >
            {copied ? "Copied" : "Copy"}
          </button>
        </div>
      )}
      {!title && !language && (
        <button
          onClick={handleCopy}
          className={cn(
            "absolute right-2 top-2 rounded px-2.5 py-1 text-xs font-medium transition-all",
            copied
              ? "bg-emerald-600/20 text-emerald-400"
              : "bg-white/[0.06] text-gray-500 hover:bg-white/10 hover:text-gray-300 opacity-0 group-hover:opacity-100",
          )}
        >
          {copied ? "Copied" : "Copy"}
        </button>
      )}
      <pre className="overflow-x-auto p-4 text-sm leading-relaxed">
        <code className="text-gray-300 font-mono">{code}</code>
      </pre>
    </div>
  );
}
