'use client';
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { CssBaseline, GlobalStyles } from '@mui/material';
import useMediaQuery from '@mui/material/useMediaQuery';

type ThemeMode = 'light' | 'dark';

interface ThemeContextType {
    mode: ThemeMode;
    toggleMode: () => void;
}

const ThemeContext = createContext<ThemeContextType>({
    mode: 'light',
    toggleMode: () => {},
});

export const useThemeMode = () => useContext(ThemeContext);

interface CustomThemeProviderProps {
    children: ReactNode;
}

export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({ children }) => {
    // SSR-sichere System-Präferenz-Erkennung
    const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)', { noSsr: true });

    // SSR-sichere Initialisierung
    const [mode, setMode] = useState<ThemeMode>('light');
    const [mounted, setMounted] = useState(false);

    // Nach dem ersten Render ausführen (SSR-sicher)
    useEffect(() => {
        setMounted(true);

        if (typeof window !== 'undefined') {
            const savedMode = localStorage.getItem('themeMode') as ThemeMode;
            if (savedMode === 'light' || savedMode === 'dark') {
                setMode(savedMode);
            } else {
                setMode(prefersDarkMode ? 'dark' : 'light');
            }
        }
    }, [prefersDarkMode]);

    // Mode in localStorage speichern
    useEffect(() => {
        if (mounted && typeof window !== 'undefined') {
            localStorage.setItem('themeMode', mode);
        }
    }, [mode, mounted]);

    // Browser-only DOM-Manipulation
    useEffect(() => {
        if (mounted && typeof window !== 'undefined') {
            const backgroundColor = mode === 'dark' ? '#121212' : '#fafafa';

            // Warten bis DOM geladen ist
            const updateBackground = () => {
                document.documentElement.style.setProperty('--background-color', backgroundColor);
                document.documentElement.style.backgroundColor = backgroundColor;
                document.body.style.backgroundColor = backgroundColor;

                const root = document.getElementById('root');
                if (root) {
                    root.style.backgroundColor = backgroundColor;
                }
            };

            // Sofort ausführen
            updateBackground();

            // Nach einem kurzen Delay nochmal (für hartnäckige Cases)
            const timeoutId = setTimeout(updateBackground, 100);

            return () => clearTimeout(timeoutId);
        }
    }, [mode, mounted]);

    const toggleMode = () => {
        setMode(prevMode => prevMode === 'light' ? 'dark' : 'light');
    };

    // Theme basierend auf Mode erstellen
    const theme = React.useMemo(() =>
            createTheme({
                palette: {
                    mode,
                    primary: {
                        main: '#0fd13f', // Grüne NavBar
                        light: mode === 'dark' ? '#4caf50' : '#42a5f5',
                        dark: mode === 'dark' ? '#388e3c' : '#1565c0',
                        contrastText: '#fff',
                    },
                    secondary: {
                        main: mode === 'dark' ? '#bb86fc' : '#9c27b0',
                        light: mode === 'dark' ? '#d7aefb' : '#ba68c8',
                        dark: mode === 'dark' ? '#985eff' : '#7b1fa2',
                        contrastText: '#fff',
                    },
                    background: {
                        default: mode === 'dark' ? '#121212' : '#fafafa',
                        paper: mode === 'dark' ? '#1e1e1e' : '#ffffff',
                    },
                    text: {
                        primary: mode === 'dark' ? '#ffffff' : '#000000',
                        secondary: mode === 'dark' ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)',
                    },
                    homepage: mode === 'dark' ? '#1e1e1e' : '#f4f4f4',
                },
                components: {
                    MuiCssBaseline: {
                        styleOverrides: {
                            html: {
                                backgroundColor: `${mode === 'dark' ? '#121212' : '#fafafa'} !important`,
                                transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
                            },
                            body: {
                                backgroundColor: `${mode === 'dark' ? '#121212' : '#fafafa'} !important`,
                                transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
                                margin: 0,
                            },
                        },
                    },
                    MuiAppBar: {
                        styleOverrides: {
                            colorPrimary: {
                                backgroundColor: mode === 'dark' ? '#388e3c' : '#0fd13f',
                                color: '#ffffff',
                            },
                        },
                    },
                },
            }),
        [mode]
    );

    // Aggressive GlobalStyles mit CSS-Variablen
    const globalStyles = mounted ? (
        <GlobalStyles
            styles={{
                ':root': {
                    '--background-color': mode === 'dark' ? '#121212' : '#fafafa',
                    '--text-color': mode === 'dark' ? '#ffffff' : '#000000',
                },
                '*': {
                    boxSizing: 'border-box',
                },
                'html, body, #root': {
                    backgroundColor: `var(--background-color) !important`,
                    color: `var(--text-color) !important`,
                    transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1), color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
                    margin: 0,
                    padding: 0,
                    minHeight: '100vh',
                },
                'div, section, main, article': {
                    backgroundColor: 'transparent',
                },
            }}
        />
    ) : null;

    // SSR-Fallback während mounted = false
    if (!mounted) {
        return (
            <ThemeProvider theme={createTheme({ palette: { mode: 'light' } })}>
                <CssBaseline />
                {children}
            </ThemeProvider>
        );
    }

    return (
        <ThemeContext.Provider value={{ mode, toggleMode }}>
            <ThemeProvider theme={theme}>
                <CssBaseline enableColorScheme />
                {globalStyles}
                {children}
            </ThemeProvider>
        </ThemeContext.Provider>
    );
};
