import { useCallback, useEffect, useRef } from 'react'
import Editor, { type BeforeMount } from '@monaco-editor/react'
import { resolutionFlowTheme, THEME_ID } from '@/components/tree-editor/code-mode/resolutionFlowTheme'
import { Spinner } from '@/components/common/Spinner'

interface Props {
  value: string
  onChange: (value: string) => void
  disabled?: boolean
}

export function ScriptBodyEditor({ value, onChange, disabled }: Props) {
  const lastValueRef = useRef(value)
  useEffect(() => {
    lastValueRef.current = value
  }, [value])

  const handleBeforeMount: BeforeMount = useCallback((monaco) => {
    // Register our dark theme if not already defined
    monaco.editor.defineTheme(THEME_ID, resolutionFlowTheme)
  }, [])

  const handleChange = useCallback((v: string | undefined) => {
    const next = v ?? ''
    // Only propagate user-initiated edits, not echoes from external value prop changes
    if (next !== lastValueRef.current) {
      onChange(next)
    }
  }, [onChange])

  return (
    <div className="rounded-xl border border-border overflow-hidden">
      <Editor
        height="300px"
        language="powershell"
        theme={THEME_ID}
        value={value}
        onChange={handleChange}
        beforeMount={handleBeforeMount}
        loading={
          <div className="flex h-[300px] items-center justify-center bg-card">
            <Spinner size="sm" className="h-6 w-6 border-t-foreground" />
          </div>
        }
        options={{
          minimap: { enabled: false },
          fontSize: 13,
          fontFamily: "'JetBrains Mono', monospace",
          lineNumbers: 'on',
          wordWrap: 'on',
          scrollBeyondLastLine: false,
          renderLineHighlight: 'line',
          tabSize: 4,
          insertSpaces: true,
          automaticLayout: true,
          readOnly: disabled,
          padding: { top: 12, bottom: 12 },
          scrollbar: {
            verticalScrollbarSize: 8,
            horizontalScrollbarSize: 8,
          },
        }}
      />
    </div>
  )
}
