import { useEffect, useMemo, useState } from "react"
import { gql, useQuery } from "~/generated/graphql"
import { Theme } from "../models/enums.generated"
import type { Preferences } from "../models"

const DARK_MODE_QUERY = gql<"DarkModeHookQuery">`
  query DarkModeHookQuery {
    preferences {
      theme
    }
  }
`

export function useDarkMode(): boolean {
  const { data } = useQuery(DARK_MODE_QUERY)
  const pref = data?.preferences.theme ?? loadPref()?.theme
  const media = useMemo(() => window.matchMedia("(prefers-color-scheme: dark)"), [])
  const [systemDarkMode, setSystemDarkMode] = useState(media.matches)

  useEffect(() => {
    const handler = () => setSystemDarkMode(media.matches)
    media.addEventListener("change", handler)
    return () => media.removeEventListener("change", handler)
  })

  return pref === Theme.System ? systemDarkMode : pref === Theme.Dark ?? false
}

function loadPref(): Preferences | undefined {
  try {
    return JSON.parse(localStorage.getItem("preferences") ?? "{}")
  } catch {}
}
