import { useEffect, type ReactNode } from 'react'
import { isAbortError } from '../lib/api'
import { getTenantDomain } from '../lib/config'
import { resolveTenantByDomain } from '../services/tenantService'
import { applyBusinessPrimaryColor, resetBusinessPrimaryColor } from '../utils/applyBusinessTheme'
import { normalizeBusinessPrimaryColorId } from '../utils/businessPrimaryColors'

function applyThemeMode(mode: 'light' | 'dark' | undefined) {
  document.documentElement.setAttribute(
    'data-theme',
    mode === 'dark' ? 'dark' : 'light',
  )
}

export function CustomerThemeProvider({ children }: { children: ReactNode }) {
  useEffect(() => {
    const controller = new AbortController()
    const domain = getTenantDomain()

    async function loadTheme() {
      try {
        const tenant = await resolveTenantByDomain(domain, controller.signal)
        if (controller.signal.aborted) return
        applyBusinessPrimaryColor(
          normalizeBusinessPrimaryColorId(tenant.primaryColor),
        )
        applyThemeMode(tenant.themeMode)
      } catch (err) {
        if (isAbortError(err)) return
        applyBusinessPrimaryColor(undefined)
        applyThemeMode('light')
      }
    }

    void loadTheme()

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

  return children
}
