'use client'

import * as React from 'react'
import type { DevModeCodeLanguage } from './dev-mode-types'
import { javascript } from '@codemirror/lang-javascript'
import { json } from '@codemirror/lang-json'
import { EditorView } from '@codemirror/view'
import { githubLight } from '@uiw/codemirror-theme-github'
import CodeMirror from '@uiw/react-codemirror'

const codeMirrorSetup = {
  lineNumbers: true,
  foldGutter: false,
  highlightActiveLine: true,
  highlightActiveLineGutter: true
}

const compactCodeTheme = EditorView.theme({
  '&': {
    fontSize: '12px'
  },
  '.cm-content': {
    padding: '10px 0 14px'
  },
  '.cm-gutters': {
    padding: '0 0 14px'
  },
  '.cm-content, .cm-gutters': {
    lineHeight: '1.5'
  },
  '.cm-lineNumbers .cm-gutterElement': {
    padding: '0 12px'
  },
  '.cm-line': {
    padding: '0 16px'
  },
  '.cm-scroller': {
    fontFamily:
      'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'
  }
})

interface DevModeCodeMirrorProps {
  code: string
  language: DevModeCodeLanguage
}

export default function DevModeCodeMirror({ code, language }: DevModeCodeMirrorProps) {
  const extensions = React.useMemo(
    () =>
      language === 'json'
        ? [json(), compactCodeTheme]
        : [javascript({ typescript: true, jsx: language === 'tsx' }), compactCodeTheme],
    [language]
  )

  return (
    <CodeMirror
      value={code}
      editable={false}
      readOnly
      basicSetup={codeMirrorSetup}
      extensions={extensions}
      theme={githubLight}
      className="flex-1 [&>.cm-editor]:h-full"
    />
  )
}
