"use client"

import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
import { usePreferences } from "@/contexts/preferences-context"

export function ThemeToggle() {
    const { theme, setTheme } = useTheme()
    const { preferences, updatePreferences, loading: prefsLoading } = usePreferences()
    const [mounted, setMounted] = React.useState(false)

    React.useEffect(() => {
        setMounted(true)
    }, [])

    // Sync theme from preferences when loaded
    React.useEffect(() => {
        if (!prefsLoading && preferences.theme && mounted) {
            // Only sync if the preference is different from current theme
            if (preferences.theme !== theme && preferences.theme !== "system") {
                setTheme(preferences.theme)
            }
        }
    }, [prefsLoading, preferences.theme, mounted])

    const handleToggle = () => {
        const newTheme = theme === "dark" ? "light" : "dark"
        setTheme(newTheme)
        // Persist to backend
        updatePreferences({ theme: newTheme })
    }

    if (!mounted) {
        return (
            <Button variant="ghost" size="icon" className="h-9 w-9">
                <Sun className="h-4 w-4" />
            </Button>
        )
    }

    return (
        <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9"
            onClick={handleToggle}
        >
            {theme === "dark" ? (
                <Sun className="h-4 w-4" />
            ) : (
                <Moon className="h-4 w-4" />
            )}
            <span className="sr-only">Toggle theme</span>
        </Button>
    )
}
