"use client"

import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from "react"

const WEBSITE_THEME_KEY = "crm-website-theme"

const themeClasses: Record<string, string> = {
  default: "theme-default",
  spidey: "theme-spidey",
}

interface WebsiteThemeContextValue {
  websiteTheme: string
  setWebsiteTheme: (theme: string) => Promise<void>
  loading: boolean
}

const WebsiteThemeContext = createContext<WebsiteThemeContextValue | null>(null)

function applyWebsiteTheme(theme: string) {
  const prefix = "theme-"
  const root = document.documentElement
  const classes = root.className.split(" ").filter((c) => !c.startsWith(prefix))
  const cls = themeClasses[theme]
  if (cls) {
    classes.push(cls)
  }
  root.className = classes.join(" ").trim()
}

function getStoredTheme(): string | null {
  if (typeof window === "undefined") return null
  return localStorage.getItem(WEBSITE_THEME_KEY)
}

function storeTheme(theme: string) {
  if (typeof window === "undefined") return
  localStorage.setItem(WEBSITE_THEME_KEY, theme)
}

export function WebsiteThemeProvider({ children }: { children: ReactNode }) {
  const [websiteTheme, setWebsiteThemeState] = useState<string>("default")
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const stored = getStoredTheme()
    if (stored) {
      setWebsiteThemeState(stored)
      applyWebsiteTheme(stored)
      setLoading(false)
      return
    }
    fetch("/api/settings/website-theme")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        const theme = data?.websiteTheme || "default"
        setWebsiteThemeState(theme)
        storeTheme(theme)
        applyWebsiteTheme(theme)
      })
      .catch(() => {
        applyWebsiteTheme("default")
      })
      .finally(() => setLoading(false))
  }, [])

  const setWebsiteTheme = useCallback(async (theme: string) => {
    setWebsiteThemeState(theme)
    storeTheme(theme)
    applyWebsiteTheme(theme)
    try {
      await fetch("/api/settings/website-theme", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ websiteTheme: theme }),
      })
    } catch {
      console.warn("Failed to persist website theme")
    }
  }, [])

  return (
    <WebsiteThemeContext.Provider value={{ websiteTheme, setWebsiteTheme, loading }}>
      {children}
    </WebsiteThemeContext.Provider>
  )
}

export function useWebsiteTheme() {
  const ctx = useContext(WebsiteThemeContext)
  if (!ctx) throw new Error("useWebsiteTheme must be used within WebsiteThemeProvider")
  return ctx
}
