import { Editor } from "@monaco-editor/react"
import { memo } from "react"
import { gql, useQuery } from "~/generated/graphql"
import { getActiveFile, useSelector } from "../store"
import type { ReduxFile } from "../store/state"
import { useDebouncedValue } from "~/shared/hooks/useDebouncedValue"
import { useMonacoOptions, useMonacoTheme } from "../editor/useOptions"

const PREVIEW_COMPILED = gql<"PreviewCompiledCode">`
  query PreviewCompiledCode($file: String!) {
    compileCode(code: $file, includeGlobal: false, cache: false, compressed: false)
  }
`

const PreviewTab = memo<{
  file: ReduxFile
}>(({ file }) => {
  const delayedFile = useDebouncedValue(file.sections[0].code, 1000)
  const theme = useMonacoTheme()
  const options = useMonacoOptions({
    readOnly: true,
    minimap: false,
  })

  const { data } = useQuery(PREVIEW_COMPILED, {
    fetchPolicy: "no-cache",
    skip: !delayedFile,
    variables: {
      file: delayedFile,
    },
  })

  if (!data) return null

  return (
    <Editor
      height="100%"
      defaultValue={data.compileCode}
      language="css"
      theme={theme}
      options={options}
    />
  )
})

export const Preview = memo<{
  className?: string
  active: boolean
}>(({ className, active }) => {
  const style = useSelector(getActiveFile)

  return (
    <div style={{ height: "100%" }} className={className}>
      {style && active && <PreviewTab file={style} />}
    </div>
  )
})
