'use client'

import { isValidElement, type ReactNode } from 'react'
import { CopyButton } from './CopyButton'

type CodeWrapperProps = {
  language?: string
  children?: ReactNode
}

function getTextContent(node: ReactNode): string {
  if (node === null || typeof node === 'boolean') return ''
  if (typeof node === 'string' || typeof node === 'number') return String(node)
  if (Array.isArray(node)) return node.map(getTextContent).join('')
  if (isValidElement(node)) {
    const props = node.props as { children?: ReactNode }
    return getTextContent(props.children)
  }
  return ''
}

export function CodeWrapper({ language, children }: CodeWrapperProps) {
  const text = getTextContent(children).replace(/\n$/, '')
  const lineCount = text.length === 0 ? 1 : text.split('\n').length

  return (
    <div className="bg-foreground/10 rounded-md overflow-x-auto border border-border bg-fg/10">
      <div
        className="flex items-center gap-2 px-2 h-6 border-b border-border w-full"
        aria-hidden="true"
      >
        <div className="space-x-1">
          <span className="w-2 h-2 bg-border rounded-full inline-block"></span>
          <span className="w-2 h-2 bg-border rounded-full inline-block"></span>
          <span className="w-2 h-2 bg-border rounded-full inline-block"></span>
        </div>
        <span className="text-xs text-fg-dim font-mono">{language ?? 'code'}</span>
        <CopyButton textToCopy={text} className="ml-auto" />
      </div>

      <div className="flex">
        <div className="select-none text-right py-2 px-3 border-r border-border text-white font-mono text-sm leading-6 min-w-6">
          {Array.from({ length: lineCount }, (_, i) => (
            <span className="block" key={i}>
              {i + 1}
            </span>
          ))}
        </div>

        <pre className="flex-1 p-2 m-0 overflow-x-auto text-fg-dim font-mono text-sm leading-6">
          {children}
        </pre>
      </div>
    </div>
  )
}
