import * as React from 'react'
import { CheckIcon, CopyIcon } from 'lucide-react'

import { cn } from './utils'

/* ------------------------------------------------------------------ */
/*  CodeBlock                                                          */
/* ------------------------------------------------------------------ */

export interface CodeBlockProps extends React.ComponentProps<'div'> {
  /** The code string to display */
  code: string
  /** Language label (e.g. "json", "sql", "yaml") */
  language?: string
  /** Show line numbers */
  showLineNumbers?: boolean
  /** Show copy-to-clipboard button (default: true) */
  showCopyButton?: boolean
  /** Maximum height with overflow scroll */
  maxHeight?: string
}

function CodeBlock({
  className,
  code,
  language,
  showLineNumbers = false,
  showCopyButton = true,
  maxHeight,
  ...props
}: CodeBlockProps) {
  const [copied, setCopied] = React.useState(false)
  const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)

  const handleCopy = React.useCallback(() => {
    void navigator.clipboard.writeText(code).then(() => {
      setCopied(true)

      if (timeoutRef.current !== null) {
        clearTimeout(timeoutRef.current)
      }

      timeoutRef.current = setTimeout(() => {
        setCopied(false)
        timeoutRef.current = null
      }, 2000)
    })
  }, [code])

  React.useEffect(() => {
    return () => {
      if (timeoutRef.current !== null) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  const lines = code.split('\n')

  return (
    <div
      data-slot="code-block"
      className={cn(
        'overflow-hidden rounded-xl border border-border-glass bg-surface-secondary/50 backdrop-blur-[20px]',
        className
      )}
      {...props}
    >
      {/* Header */}
      {(language || showCopyButton) && (
        <div className="flex items-center justify-between border-b border-border-glass px-4 py-2">
          <span className="text-xs font-medium text-foreground-muted">{language ?? ''}</span>
          {showCopyButton && (
            <button
              type="button"
              aria-label="Copy code"
              onClick={handleCopy}
              className={cn(
                'inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[11px] font-medium transition-colors',
                copied
                  ? 'text-accent-emerald'
                  : 'text-foreground-secondary hover:bg-glass-hover hover:text-foreground'
              )}
            >
              {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
              {copied ? 'Copied!' : 'Copy'}
            </button>
          )}
        </div>
      )}

      {/* Code content */}
      <div
        className="overflow-x-auto"
        style={maxHeight ? { maxHeight, overflowY: 'auto' } : undefined}
      >
        <pre className="p-4 text-[13px] leading-relaxed">
          <code className="font-mono text-foreground">
            {showLineNumbers
              ? lines.map((line, i) => (
                  <span key={i} className="table-row">
                    <span className="table-cell select-none pr-4 text-right text-foreground-muted">
                      {i + 1}
                    </span>
                    <span className="table-cell">{line}</span>
                    {'\n'}
                  </span>
                ))
              : code}
          </code>
        </pre>
      </div>
    </div>
  )
}

export { CodeBlock }
