'use client';

import { useAppSelector } from "@/redux/store"
import { setThemeType } from '@/redux/features/theme-slice'
import { useDispatch } from "react-redux"
import { AppDispatch } from '@/redux/store';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Alert from '@/components/common/alert'
import { ReactNode, useEffect } from 'react'

// this layout contain global state managment ( that should wrapp all pages )
export default function LocaleLayout({children} : { children : ReactNode }) {

  const dispatch = useDispatch<AppDispatch>();

  // init redux states that need localstorage
  useEffect(() => {
    dispatch(setThemeType(
      localStorage.getItem('theme') ? localStorage.getItem('theme') : 'light'
    ))
  }, [])

  // get redux states
  const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType)

  // handle the mui theme provider
  const theme = {
    'primary': themeType == 'light' ? '#fff' : '#121212', // primary / primary-dark
    'secondary': themeType == 'light' ? '#D9D9D9' : '#D9D9D9', // secondary / secondary-lite
    'text': themeType == 'light' ? '#000000' : '#ffffff' , // text
    'success': themeType == 'light' ? '#38C172' : '#38C172',
    'error': themeType == 'light' ? '#E3342F' : '#E3342F', // danger
    'warning': themeType == 'light' ? '#FFED4A' : '#FFED4A',
    'info': themeType == 'light' ? '#026af2' : '#026af2',
    'paper': themeType == 'light' ?  '#fff' : '#121212',
  }

  // set mui theme
  const MUITheme = createTheme({
    typography: {
      fontFamily: [
        'Poppins'
      ].join(',')
    },
    palette: {
      background : {
        default: theme.primary,
        paper: theme.primary,
      },
      primary : {
        main: theme.primary,
        dark: "#1D1D1D",
        light: "#ffffff"
      },
      secondary: {
        main: theme.secondary,
        light: "#B90000",
      },
      text: {
        primary : theme.text,
      },
      success: {
        main: theme.success,
      },
      warning: {
        main: theme.warning
      },
      error: {
        main: theme.error,
      },
      info: {
        main: theme.info,
      },
    }
  });

  // wrap the layout with global components
  function GlobalComponentsHOC({children} : { children : ReactNode }) {

    // get redux states
    const alertPayload = useAppSelector((state) => state.alertReducer.value)
  
    return (
      <>
        <Alert payload={alertPayload} />
        {children}
      </>
    )
  }

  return (
    <body className={themeType}>
      <ThemeProvider theme={MUITheme}>
        <GlobalComponentsHOC>
          {children}
        </GlobalComponentsHOC>
      </ThemeProvider>
    </body>
  );
}