"use client";

import { useState, useCallback } from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";

interface CodeBlockProps {
  code: string;
  language?: string;
  label?: string;
}

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

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

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        handleCopy();
      }
    },
    [handleCopy]
  );

  const codeLabel = label || `${language} code example`;

  // Map common language names to Prism language identifiers
  const languageMap: Record<string, string> = {
    python: "python",
    javascript: "javascript",
    typescript: "typescript",
    java: "java",
    cpp: "cpp",
    c: "c",
    go: "go",
    rust: "rust",
  };

  const prismLanguage = languageMap[language.toLowerCase()] || language;

  return (
    <div className="relative group">
      <div className="absolute right-2 top-2 z-10 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
        <button
          type="button"
          onClick={handleCopy}
          onKeyDown={handleKeyDown}
          aria-label={copied ? "Code copied to clipboard" : "Copy code to clipboard"}
          className="px-2 py-1 text-xs bg-[var(--muted)] rounded hover:bg-[var(--secondary)] focus:bg-[var(--secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)] transition-colors"
        >
          {copied ? "Copied!" : "Copy"}
        </button>
        <span role="status" aria-live="polite" className="sr-only">
          {copied ? "Code copied to clipboard" : ""}
        </span>
      </div>
      <div className="text-xs text-[var(--muted-foreground)] mb-1 capitalize">
        {language}
      </div>
      <div aria-label={codeLabel} tabIndex={0} className="rounded-lg overflow-hidden">
        <SyntaxHighlighter
          language={prismLanguage}
          style={oneDark}
          customStyle={{
            margin: 0,
            padding: "1rem",
            fontSize: "0.875rem",
            borderRadius: "0.5rem",
          }}
          showLineNumbers={false}
        >
          {code.trim()}
        </SyntaxHighlighter>
      </div>
    </div>
  );
}
