'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React, { useMemo, useState, useEffect } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { useCustomizerStore } from '@/features/dashboard/store/useCustomizerStore';
import { LicenseInfo } from '@mui/x-license';
import { AuthInitializer } from '@/features/login/components/AuthInitializer';

const PERPETUAL_LICENSE_KEY = 'e0d9bb8070ce0054c9d9ecb6e82cb58fTz0wLEU9MzI0NzIxNDQwMDAwMDAsUz1wcmVtaXVtLExNPXBlcnBldHVhbCxLVj0y';
try {
    LicenseInfo.setLicenseKey(PERPETUAL_LICENSE_KEY);
} catch (error) {
    console.error('Failed to set MUI license key:', error);
}


export default function Providers({ children }: Readonly<{ children: React.ReactNode }>) {
    const [queryClient] = useState(() => new QueryClient());
    const [mounted, setMounted] = useState(false);
    const activeMode = useCustomizerStore((state) => state.activeMode);
    const isHydrated = useCustomizerStore((state) => state.isHydrated);

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

    const safeMode = mounted && isHydrated ? activeMode : 'light';

    const theme = useMemo(
        () =>
            createTheme({
                palette: {
                    mode: safeMode,
                    primary: {
                        main: '#5d87ff',
                        light: '#ecf2ff',
                        dark: '#4570ea',
                    },
                    secondary: {
                        main: '#49beff',
                        light: '#e8f7ff',
                        dark: '#23afdb',
                    },
                    ...(safeMode === 'dark'
                        ? {
                            text: {
                                primary: '#ffffff',
                                secondary: '#b0bcc8',
                            },
                            background: {
                                default: '#0b1426',
                                paper: '#111c2e',
                            },
                        }
                        : {
                            text: {
                                primary: '#1a1a1a',
                                secondary: '#4a5568',
                            },
                            background: {
                                default: '#ffffff',
                                paper: '#ffffff',
                            },
                        }),
                },
                typography: {
                    fontFamily: '"Plus Jakarta Sans", "Helvetica", "Arial", sans-serif',
                    h1: { fontWeight: 600 },
                    h6: { fontWeight: 600 },
                    body1: { fontSize: '0.875rem', fontWeight: 400 },
                },
                components: {
                    MuiCssBaseline: {
                        styleOverrides: {
                            body: {
                                fontFamily: "var(--font-plus-jakarta), 'Plus Jakarta Sans', sans-serif",
                            },
                        },
                    },
                    MuiTypography: {
                        styleOverrides: {
                            root: ({ theme }) => ({
                                ...(theme.palette.mode === 'light' && {
                                    color: theme.palette.text.primary,
                                }),
                            }),
                        },
                    },
                },
            }),
        [safeMode]
    );

    return (
        <QueryClientProvider client={queryClient}>
            <AuthInitializer>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                {children}
            </ThemeProvider>
            </AuthInitializer>
        </QueryClientProvider>
    );
}
