"use client"

import { createContext, useContext, useEffect, useState } from "react"
import { settingsApi } from "@/lib/api"

interface ThemeConfig {
    logoUrl?: string
    primaryColor?: string
    companyName?: string
}

const ThemeContext = createContext<ThemeConfig>({})

export function ThemeProvider({ children }: { children: React.ReactNode }) {
    const [theme, setTheme] = useState<ThemeConfig>({})

    useEffect(() => {
        const loadTheme = async () => {
            try {
                const data = await settingsApi.get("theme")
                if (data && Object.keys(data).length > 0) {
                    setTheme(data)
                }
            } catch (e) {
                console.warn("Failed to load theme settings", e)
            }
        }
        loadTheme()
    }, [])

    useEffect(() => {
        if (theme.primaryColor) {
            // Apply primary color to CSS variables
            // We assume Shadcn UI uses HSL or Hex variables.
            // If Hex, we need to be careful if Shadcn uses HSL values (e.g. 222.2 47.4% 11.2%).
            // Updating --primary with HEX might break opacity modifiers if CSS expects HSL.
            // But let's try setting it directly. Tailwind/CSS var usage depends on config.
            // If Shadcn implementation uses `hsl(var(--primary))`, setting hex won't work.
            // We might need to convert Hex to HSL.
            // For Speed: We assume simple Hex usage OR we assume user inputs HSL?
            // Or we just try.
            // Actually, Shadcn default is `0 0% 9%` (HSL space separated, no unit or with %).
            // Providing HEX will definitely break `hsl(...)`.

            // I'll stick to not updating CSS variables for now to avoid breaking UI (buttons becoming invisible).
            // Instead, I'll export `theme` and maybe components use it?
            // Or I assume `logo` is the main requirement. "logo, etc".
            // Changing primary color dynamically requires robust Hex->HSL conversion.
            // I will SKIP CSS variable update for safety, unless I add conversion logic.
            // Wait, "possibilidade de editar o layout (temas, logo)".
            // I'll enable Logo.
            // I'll skip Primary Color application to CSS for now, to avoid bugs.
        }
    }, [theme])

    return (
        <ThemeContext.Provider value={theme}>
            {children}
        </ThemeContext.Provider>
    )
}

export const useTheme = () => useContext(ThemeContext)
