import { lazy, Suspense } from 'react'

import type { DiffEditorProps, EditorProps } from '@monaco-editor/react'

const MonacoEditor = lazy(async () => {
  const mod = await import('@monaco-editor/react')
  return { default: mod.default }
})

const MonacoDiffEditor = lazy(async () => {
  const mod = await import('@monaco-editor/react')
  return { default: mod.DiffEditor }
})

function MonacoLoading({
  height,
  width,
  className,
  loading,
}: {
  height?: string | number
  width?: string | number
  className?: string
  loading?: React.ReactNode
}) {
  return (
    <div
      className={className}
      style={{ height: height ?? '100%', width: width ?? '100%' }}
    >
      {loading ?? (
        <div className="flex h-full min-h-[280px] items-center justify-center bg-[#111111] text-sm text-slate-400">
          正在加载编辑器...
        </div>
      )}
    </div>
  )
}

export function LazyEditor(props: EditorProps) {
  return (
    <Suspense
      fallback={
        <MonacoLoading
          height={props.height}
          width={props.width}
          className={props.className}
          loading={props.loading}
        />
      }
    >
      <MonacoEditor {...props} />
    </Suspense>
  )
}

export function LazyDiffEditor(props: DiffEditorProps) {
  return (
    <Suspense
      fallback={
        <MonacoLoading
          height={props.height}
          width={props.width}
          className={props.className}
          loading={props.loading}
        />
      }
    >
      <MonacoDiffEditor {...props} />
    </Suspense>
  )
}
