'use client'

// React Imports
import { useMemo } from 'react'

// MUI Imports
import { deepmerge } from '@mui/utils'
import { ThemeProvider, createTheme, darken, lighten } from '@mui/material/styles'
import { AppRouterCacheProvider } from '@mui/material-nextjs/v14-appRouter'
import CssBaseline from '@mui/material/CssBaseline'
import type {} from '@mui/material/themeCssVarsAugmentation' //! Do not remove this import otherwise you will get type errors while making a production build
import type {} from '@mui/lab/themeAugmentation' //! Do not remove this import otherwise you will get type errors while making a production build

// Third-party Imports
import { useMedia } from 'react-use'
import stylisRTLPlugin from 'stylis-plugin-rtl'

// Type Imports
import type { ChildrenType, Direction, SystemMode } from '@core/types'

// Component Imports
import ModeChanger from './ModeChanger'

// Config Imports
import themeConfig from '@configs/themeConfig'
import primaryColorConfig from '@configs/primaryColorConfig'

// Hook Imports
import { useSettings } from '@core/hooks/useSettings'

// Core Theme Imports
import defaultCoreTheme from '@core/theme'

// Helper function to calculate background color from primary color
const calculateBackground = (primaryColor: string, mode: 'light' | 'dark') => {
  if (mode === 'dark') {
    // For dark mode: create a darker background based on primary color
    // Mix primary color with black to create a dark background
    return darken(primaryColor, 0.85)
  } else {
    // For light mode: create a lighter background based on primary color
    // Mix primary color with white to create a light background
    return lighten(primaryColor, 0.95)
  }
}

// Helper function to calculate paper background color
const calculatePaperBackground = (primaryColor: string, mode: 'light' | 'dark') => {
  if (mode === 'dark') {
    // For dark mode: slightly lighter than default background
    return darken(primaryColor, 0.75)
  } else {
    // For light mode: white or very light tint
    return '#FFFFFF'
  }
}

// Helper function to convert hex color to RGB channel string (e.g., "47 51 73")
const hexToRgbChannel = (hex: string): string => {
  // Remove # if present
  const cleanHex = hex.replace('#', '')
  
  // Parse RGB values
  const r = parseInt(cleanHex.substring(0, 2), 16)
  const g = parseInt(cleanHex.substring(2, 4), 16)
  const b = parseInt(cleanHex.substring(4, 6), 16)
  
  return `${r} ${g} ${b}`
}

type Props = ChildrenType & {
  direction: Direction
  systemMode: SystemMode
}

const CustomThemeProvider = (props: Props) => {
  // Props
  const { children, direction, systemMode } = props

  // Hooks
  const { settings } = useSettings()
  const isDark = useMedia('(prefers-color-scheme: dark)', systemMode === 'dark')

  // Vars
  const isServer = typeof window === 'undefined'
  let currentMode: SystemMode

  if (isServer) {
    currentMode = systemMode
  } else {
    if (settings.mode === 'system') {
      currentMode = isDark ? 'dark' : 'light'
    } else {
      currentMode = settings.mode as SystemMode
    }
  }

  // Get selected palette
  const selectedPaletteId = settings.primaryColorPaletteId || primaryColorConfig[0].id
  const selectedPalette = primaryColorConfig.find(p => p.id === selectedPaletteId) || primaryColorConfig[0]

  // Merge the primary color scheme override with the core theme
  const theme = useMemo(() => {
    const lightPrimary = selectedPalette.light.main
    const darkPrimary = selectedPalette.dark.main

    const lightPaperBg = calculatePaperBackground(lightPrimary, 'light')
    const darkPaperBg = calculatePaperBackground(darkPrimary, 'dark')

    const newTheme = {
      colorSchemes: {
        light: {
          palette: {
            primary: {
              main: lightPrimary,
              light: selectedPalette.light.light,
              dark: selectedPalette.light.dark
            },
            background: {
              default: calculateBackground(lightPrimary, 'light'),
              paper: lightPaperBg,
              paperChannel: hexToRgbChannel(lightPaperBg)
            }
          }
        },
        dark: {
          palette: {
            primary: {
              main: darkPrimary,
              light: selectedPalette.dark.light,
              dark: selectedPalette.dark.dark
            },
            background: {
              default: calculateBackground(darkPrimary, 'dark'),
              paper: darkPaperBg,
              paperChannel: hexToRgbChannel(darkPaperBg)
            }
          }
        }
      },
      cssVariables: {
        colorSchemeSelector: 'data'
      }
    }

    const coreTheme = deepmerge(defaultCoreTheme(settings, currentMode, direction), newTheme)

    return createTheme(coreTheme)
  }, [selectedPalette, settings.skin, currentMode, direction])

  return (
    <AppRouterCacheProvider
      options={{
        prepend: true,
        ...(direction === 'rtl' && {
          key: 'rtl',
          stylisPlugins: [stylisRTLPlugin]
        })
      }}
    >
      <ThemeProvider
        theme={theme}
        defaultMode={systemMode}
        modeStorageKey={`${themeConfig.templateName.toLowerCase().split(' ').join('-')}-mui-template-mode`}
      >
        <>
          <ModeChanger systemMode={systemMode} />
          <CssBaseline />
          {children}
        </>
      </ThemeProvider>
    </AppRouterCacheProvider>
  )
}

export default CustomThemeProvider
