import React, { useCallback, useMemo, useState } from 'react';
import { Check, Copy } from 'lucide-react';
import useRenderTracker from '../../../hooks/useRenderTracker';
import { copyTextToClipboard } from '../../../utils/clipboard';
import { highlightCode } from '../../../utils/highlightCode';

interface CodeBlockProps {
  content: string;
  language?: string;
}

const normalizeLanguage = (language?: string) => (
  language?.trim() ? language.trim().toLowerCase() : 'text'
);

const CodeBlock: React.FC<CodeBlockProps> = ({ content, language }) => {
  const [isCopied, setIsCopied] = useState(false);
  const normalizedLanguage = useMemo(() => normalizeLanguage(language), [language]);
  // Highlight synchronously via a static import. (A dynamic import was failing to
  // load its chunk inside the WordPress plugin's Shadow-DOM bundle, leaving code
  // unstyled; bundling it keeps highlighting working in both web and plugin.)
  const highlightedHtml = useMemo(
    () => highlightCode(content, normalizedLanguage),
    [content, normalizedLanguage],
  );

  useRenderTracker('CodeBlock', {
    content,
    language: normalizedLanguage,
  });

  const handleCopyClick = useCallback(async () => {
    const copied = await copyTextToClipboard(content);

    if (copied) {
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 3000);
    } else {
      console.error('Failed to copy text: unsupported environment');
    }
  }, [content]);

  return (
    <div className="code-block-container my-3 overflow-hidden rounded-lg border border-app-border bg-app-surface-muted">
      <div className="flex items-center justify-between border-b border-app-border bg-app-surface px-4 py-2 text-xs font-medium text-app-muted">
        <span className="font-mono lowercase tracking-wide">{normalizedLanguage}</span>
        <button
          type="button"
          onClick={handleCopyClick}
          className="flex min-w-[100px] items-center justify-center gap-1 rounded-md px-2 py-1 text-app-muted transition-colors hover:bg-app-surface-hover hover:text-app-text focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
        >
          {isCopied ? (
            <>
              <Check size={16} />
              Copied!
            </>
          ) : (
            <>
              <Copy size={16} />
              Copy code
            </>
          )}
        </button>
      </div>
      <pre className="m-0 overflow-x-auto bg-transparent p-4 text-[0.825rem] leading-6">
        <code
          className={`hljs language-${normalizedLanguage}`}
          dangerouslySetInnerHTML={{ __html: highlightedHtml }}
        />
      </pre>
    </div>
  );
};

export default React.memo(CodeBlock);
