import type * as monaco from "monaco-editor"
import { useAutoMemo } from "hooks.macro"
import { gql, useQuery } from "~/generated/graphql"
import { useDarkMode } from "~/shared/hooks/useDarkMode"
import { ThemeQuery } from "../SideEffect"

const EDITOR_PREFERENCES = gql<"MonacoEditorPreferences">`
  query MonacoEditorPreferences {
    preferences {
      fontFamily
      fontSize
      lineHeight
      minimap
      tabSize
    }
  }
`

export function useMonacoOptions({
  readOnly,
  minimap,
}: {
  readOnly?: boolean
  minimap?: boolean
}) {
  const prefs = useQuery(EDITOR_PREFERENCES).data?.preferences

  return useAutoMemo<monaco.editor.IStandaloneEditorConstructionOptions>({
    fontFamily: prefs?.fontFamily ?? "SF Mono, monospace",
    fontSize: prefs?.fontSize ?? 14,
    lineHeight: prefs?.lineHeight ?? 20,
    tabSize: prefs?.tabSize ?? 2,
    readOnly,
    minimap: {
      enabled: minimap ?? prefs?.minimap ?? false,
    },
  })
}

export function useMonacoTheme() {
  const prefs = useQuery(ThemeQuery)?.data?.preferences
  const darkMode = useDarkMode()
  return darkMode
    ? prefs?.darkTheme ?? "github-dark"
    : prefs?.lightTheme ?? "github-light"
}
