import { useEffect, type ReactNode } from 'react'
import { useAuth } from './AuthContext'
import { getActiveBusinessId } from '../lib/businessContext'
import { isAbortError } from '../lib/api'
import { getSettings } from '../services/settingsService'
import { applyBusinessPrimaryColor, resetBusinessPrimaryColor } from '../utils/applyBusinessTheme'
import { normalizeBusinessPrimaryColorId } from '../utils/businessPrimaryColors'

export function BusinessThemeProvider({ children }: { children: ReactNode }) {
  const { user, isLoading } = useAuth()

  useEffect(() => {
    if (isLoading) return

    if (!user || !getActiveBusinessId()) {
      resetBusinessPrimaryColor()
      return
    }

    const controller = new AbortController()

    async function loadTheme() {
      try {
        const data = await getSettings(controller.signal)
        applyBusinessPrimaryColor(
          normalizeBusinessPrimaryColorId(data.settings.branding?.primaryColor),
        )
      } catch (err) {
        if (isAbortError(err)) return
        applyBusinessPrimaryColor(undefined)
      }
    }

    void loadTheme()

    return () => {
      controller.abort()
    }
  }, [user, isLoading])

  return children
}
