"use client"

import { createContext, useContext, useEffect, useState } from "react"
import { getApiUrl } from "@/lib/api-config"

interface Preferences {
    wiki_mode: boolean
    show_ratings: boolean
    show_comments: boolean
    theme: string
    email_on_reply: boolean
    email_on_chase: boolean
    email_digest: boolean
}

interface PreferencesContextType {
    preferences: Preferences
    updatePreferences: (newPrefs: Partial<Preferences>) => Promise<void>
    loading: boolean
}

const defaultPreferences: Preferences = {
    wiki_mode: false,
    show_ratings: true,
    show_comments: true,
    theme: "system",
    email_on_reply: true,
    email_on_chase: true,
    email_digest: false,
}

const PreferencesContext = createContext<PreferencesContextType>({
    preferences: defaultPreferences,
    updatePreferences: async () => { },
    loading: false,
})

export function PreferencesProvider({ children }: { children: React.ReactNode }) {
    const [preferences, setPreferences] = useState<Preferences>(defaultPreferences)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const fetchPreferences = async () => {
            const token = localStorage.getItem("token")
            if (!token) {
                setLoading(false)
                return
            }

            try {
                const res = await fetch(`${getApiUrl()}/preferences/`, {
                    headers: { Authorization: `Bearer ${token}` }
                })
                if (res.ok) {
                    const data = await res.json()
                    // Ensure we merge with defaults in case of missing fields
                    setPreferences(prev => ({ ...prev, ...data }))
                }
            } catch (err) {
                console.error("Failed to load preferences", err)
            } finally {
                setLoading(false)
            }
        }

        fetchPreferences()
    }, [])

    const updatePreferences = async (newPrefs: Partial<Preferences>) => {
        // Optimistic update
        setPreferences(prev => ({ ...prev, ...newPrefs }))

        const token = localStorage.getItem("token")
        if (!token) return

        try {
            await fetch(`${getApiUrl()}/preferences/`, {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify(newPrefs)
            })
        } catch (err) {
            console.error("Failed to save preferences", err)
            // Optionally revert state here on error
        }
    }

    return (
        <PreferencesContext.Provider value={{ preferences, updatePreferences, loading }}>
            {children}
        </PreferencesContext.Provider>
    )
}

export const usePreferences = () => useContext(PreferencesContext)
