import { type PropsWithChildren, useMemo } from 'react'
import CssBaseline from '@mui/material/CssBaseline'
import { ThemeProvider, createTheme } from '@mui/material/styles'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ThemeControllerProvider, useThemeController } from '@/app/providers/theme-controller'

function AppThemeInner({ children }: PropsWithChildren) {
  const controller = useThemeController()

  const theme = useMemo(
    () =>
      createTheme({
        palette: (() => {
          const isDark = controller.resolvedMode === 'dark'
          const common = { mode: controller.resolvedMode }

          const text = isDark
            ? { primary: '#F2F2F2', secondary: 'rgba(242,242,242,0.72)', disabled: 'rgba(242,242,242,0.48)' }
            : { primary: '#1F1B16', secondary: 'rgba(31,27,22,0.72)', disabled: 'rgba(31,27,22,0.48)' }

          const chip = isDark ? { default: '#0E1510', paper: '#121B14' } : { default: '#F6FAF6', paper: '#FFFFFF' }

          switch (controller.scheme) {
            case 'forest':
              return {
                ...common,
                primary: { main: isDark ? '#4CAF50' : '#2E7D32' },
                secondary: { main: isDark ? '#A1887F' : '#6D4C41' },
                info: { main: isDark ? '#29B6F6' : '#0288D1' },
                success: { main: isDark ? '#66BB6A' : '#2E7D32' },
                warning: { main: isDark ? '#FFB74D' : '#ED6C02' },
                error: { main: isDark ? '#EF5350' : '#D32F2F' },
                divider: isDark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.10)',
                text,
                chip,
                background: isDark
                  ? { default: '#0E1510', paper: '#121B14' }
                  : { default: '#F6FAF6', paper: '#FFFFFF' },
              }
            case 'ocean':
              return {
                ...common,
                primary: { main: isDark ? '#42A5F5' : '#1565C0' },
                secondary: { main: isDark ? '#4DD0E1' : '#00838F' },
                info: { main: isDark ? '#4FC3F7' : '#0288D1' },
                success: { main: isDark ? '#26C6DA' : '#00838F' },
                warning: { main: isDark ? '#FFCC80' : '#ED6C02' },
                error: { main: isDark ? '#EF5350' : '#D32F2F' },
                divider: isDark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.10)',
                text,
                chip,
                background: isDark
                  ? { default: '#0B1220', paper: '#0F172A' }
                  : { default: '#F6FAFF', paper: '#FFFFFF' },
              }
            case 'berry':
              return {
                ...common,
                primary: { main: isDark ? '#BA68C8' : '#7B1FA2' },
                secondary: { main: isDark ? '#F06292' : '#C2185B' },
                info: { main: isDark ? '#64B5F6' : '#1976D2' },
                success: { main: isDark ? '#81C784' : '#2E7D32' },
                warning: { main: isDark ? '#FFB74D' : '#ED6C02' },
                error: { main: isDark ? '#EF5350' : '#D32F2F' },
                divider: isDark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.10)',
                text,
                chip,
                background: isDark
                  ? { default: '#140A17', paper: '#1B0F20' }
                  : { default: '#FFF7FD', paper: '#FFFFFF' },
              }
            case 'craft':
            default:
              return {
                ...common,
                primary: { main: isDark ? '#BCAAA4' : '#6D4C41' },
                secondary: { main: isDark ? '#FFCCBC' : '#8D6E63' },
                info: { main: isDark ? '#90CAF9' : '#1976D2' },
                success: { main: isDark ? '#A5D6A7' : '#2E7D32' },
                warning: { main: isDark ? '#FFB74D' : '#ED6C02' },
                error: { main: isDark ? '#EF9A9A' : '#D32F2F' },
                divider: isDark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.10)',
                text,
                chip,
                background: isDark
                  ? { default: '#12100F', paper: '#191615' }
                  : { default: '#FAF8F5', paper: '#FFFFFF' },
              }
          }
        })(),
        shape: { borderRadius: 12 },
        typography: {
          fontFamily: '"Segoe UI", system-ui, sans-serif',
          h4: { fontWeight: 700 },
          h5: { fontWeight: 600 },
        },
        components: {
          MuiButton: {
            styleOverrides: {
              root: { textTransform: 'none', borderRadius: 12, fontWeight: 600 },
              contained: {
                boxShadow: '0 4px 14px 0 rgba(0,0,0,0.15)',
                '&:hover': {
                  boxShadow: '0 6px 20px 0 rgba(0,0,0,0.25)',
                  transform: 'translateY(-1px)',
                },
              },
              outlined: {
                '&:hover': { boxShadow: '0 2px 8px 0 rgba(0,0,0,0.1)' },
              },
            },
          },
          MuiIconButton: {
            styleOverrides: {
              root: {
                transition: 'all 0.2s ease',
                '&:hover': { transform: 'scale(1.1)' },
              },
            },
          },
        },
      }),
    [controller.resolvedMode, controller.scheme],
  )

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {children}
    </ThemeProvider>
  )
}

export function AppProviders({ children }: PropsWithChildren) {
  const queryClient = useMemo(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 30_000,
            retry: 1,
            refetchOnWindowFocus: false,
          },
        },
      }),
    [],
  )

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeControllerProvider>
        <AppThemeInner>{children}</AppThemeInner>
      </ThemeControllerProvider>
    </QueryClientProvider>
  )
}
