import React from 'react';
import { CopyButton } from '@djangocfg/ui-core/components';
import { useResolvedTheme } from '@djangocfg/ui-core/hooks';
import PrettyCode from '../../../tools/PrettyCode';

interface CodeBlockProps {
  code: string;
  language: string;
  isUser: boolean;
  isCompact?: boolean;
}

/**
 * Markdown code block. Renders <PrettyCode> directly — its own
 * FloatingToolbar already carries the language tag and Copy action.
 *
 * Earlier versions stacked an extra <CopyButton> here too, which
 * surfaced as two copy buttons on every code fence. The fallback
 * branch below still ships its own button because the plain <pre>
 * has no toolbar of its own.
 */
export const CodeBlock: React.FC<CodeBlockProps> = ({ code, language }) => {
  const theme = useResolvedTheme();

  // Chat fences are always rendered in PrettyCode's compact mode:
  // 12px font, tighter padding, line-height 1.4. A fenced block in
  // a chat bubble shouldn't outweigh two paragraphs of body text —
  // the standalone PrettyCode story keeps the larger default for
  // docs/diff viewers.
  return (
    <div className="my-2">
      <PrettyCode
        data={code}
        language={language}
        className="text-xs"
        customBg="bg-code"
        mode={theme}
        isCompact
        // Disable click-to-scroll-isolation in chat markdown: code
        // fences here are part of an assistant reply, not a docs
        // viewer. Forcing the user to click into a small block to
        // scroll past it interrupts the reading flow. The standalone
        // PrettyCode use cases (docs, diff viewers, long code panes)
        // keep the default `true`.
        scrollIsolation={false}
      />
    </div>
  );
};

/** Simple `<pre>` fallback used when CodeBlock throws (lazy module
 *  failure, missing PrettyCode peer, etc). */
export const CodeBlockFallback: React.FC<CodeBlockProps> = ({ code, isUser }) => {
  // See CodeBlock above for the spirit of this layout — palette
  // pre-computed before render.
  const copyHoverClass = isUser
    ? 'hover:bg-white/20 text-white'
    : 'hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground';
  const copyButtonClass =
    `absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity ` +
    `h-8 w-8 ${copyHoverClass}`;

  return (
    <div className="relative group my-3">
      <CopyButton
        value={code}
        variant="ghost"
        className={copyButtonClass}
        title="Copy code"
      />
      <pre className="p-3 rounded text-xs font-mono overflow-x-auto bg-code text-code-foreground border border-code-border">
        <code>{code}</code>
      </pre>
    </div>
  );
};
