'use client';

/**
 * Enhanced code block component with:
 * - Language badge (from code-lang-detect.ts)
 * - Copy button
 * - Optional line numbers
 * - Whitespace toggle
 */

import { useState } from 'react';
import { Copy, Check, WrapText } from 'lucide-react';
import { cn } from '@/lib/utils';
import { detectLanguage, getLanguageFromTag } from '@/lib/code-lang-detect';

interface CodeBlockProps {
  children: string;
  /** Language tag from the fenced code block (e.g. "ts", "rust") */
  language?: string;
  /** Auto-detect language from content if no tag provided */
  autoDetect?: boolean;
  /** Show line numbers */
  showLineNumbers?: boolean;
  className?: string;
  /** Additional header content (e.g. file name) */
  filename?: string;
}

export function CodeBlock({
  children,
  language,
  autoDetect = true,
  showLineNumbers = false,
  className,
  filename,
}: CodeBlockProps) {
  const [copied, setCopied] = useState(false);
  const [wrap, setWrap] = useState(false);

  // Resolve language
  const langInfo = language
    ? getLanguageFromTag(language)
    : autoDetect
    ? detectLanguage(children)
    : null;

  const displayLang = langInfo?.label ?? language ?? null;

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(children);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Fallback
      const textarea = document.createElement('textarea');
      textarea.value = children;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const lines = children.split('\n');

  return (
    <div
      className={cn(
        'rounded-lg border bg-muted overflow-hidden my-2',
        className,
      )}
    >
      {/* Header bar */}
      <div className="flex items-center gap-2 px-3 py-1.5 border-b bg-muted/70">
        {/* Traffic light dots (macOS style) */}
        <div className="flex gap-1.5 -ml-1">
          <div className="h-2.5 w-2.5 rounded-full bg-red-500/60" />
          <div className="h-2.5 w-2.5 rounded-full bg-yellow-500/60" />
          <div className="h-2.5 w-2.5 rounded-full bg-green-500/60" />
        </div>

        {filename && (
          <span className="text-xs font-mono text-muted-foreground ml-1 truncate max-w-48">
            {filename}
          </span>
        )}

        <div className="ml-auto flex items-center gap-1">
          {displayLang && (
            <span className="text-xs font-mono bg-muted-foreground/10 text-muted-foreground px-1.5 py-0.5 rounded">
              {displayLang}
            </span>
          )}

          {showLineNumbers && (
            <button
              type="button"
              onClick={() => setWrap((w) => !w)}
              className={cn(
                'p-1 rounded hover:bg-muted-foreground/10 transition-colors',
                wrap && 'text-primary',
              )}
              title={wrap ? 'Disable word wrap' : 'Enable word wrap'}
            >
              <WrapText className="h-3.5 w-3.5" />
            </button>
          )}

          <button
            type="button"
            onClick={handleCopy}
            className="p-1 rounded hover:bg-muted-foreground/10 transition-colors"
            title={copied ? 'Copied!' : 'Copy code'}
          >
            {copied ? (
              <Check className="h-3.5 w-3.5 text-green-600" />
            ) : (
              <Copy className="h-3.5 w-3.5 text-muted-foreground" />
            )}
          </button>
        </div>
      </div>

      {/* Code content */}
      <div
        className={cn(
          'overflow-x-auto',
          wrap && 'whitespace-pre-wrap',
        )}
      >
        <pre className="p-3 font-mono text-sm leading-5 text-foreground/90">
          {showLineNumbers ? (
            <table className="w-full border-collapse">
              <tbody>
                {lines.map((line, i) => (
                  <tr key={i}>
                    <td className="select-none pr-3 text-right text-muted-foreground/40 text-xs w-8 align-top">
                      {i + 1}
                    </td>
                    <td className="text-foreground/90 whitespace-pre">{line}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            children
          )}
        </pre>
      </div>
    </div>
  );
}
