'use client';

import * as React from 'react';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
import { type ThemeProviderProps } from 'next-themes/dist/types';

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

// Enhanced hook for theme management with database sync
export function useThemeWithSync() {
	const [mounted, setMounted] = React.useState(false);
	const [userTheme, setUserTheme] = React.useState<'light' | 'dark' | 'system'>('system');

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

	const fetchUserTheme = async () => {
		try {
			const response = await fetch('/api/users/theme');
			if (response.ok) {
				const data = await response.json();
				setUserTheme(data.themePreference);
			}
		} catch (error) {
			console.error('Failed to fetch user theme preference:', error);
		}
	};

	const updateTheme = async (theme: 'light' | 'dark' | 'system') => {
		try {
			const response = await fetch('/api/users/theme', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({ themePreference: theme }),
			});

			if (response.ok) {
				setUserTheme(theme);
			}
		} catch (error) {
			console.error('Failed to update theme preference:', error);
		}
	};

	return {
		mounted,
		theme: userTheme,
		setTheme: updateTheme,
	};
}
