import React, { useContext, useRef, useState } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Navigator from './Navigator';
import { WidgetContainerProps } from './types';
import { ApplicationContext, MiniAppContext } from '../Context';
import Localize from './Localize';
import { defaultTheme } from '../Consts';
import {
  NavigationContainer as ReactNavigationContainer,
  NavigationContainerRef,
  NavigationIndependentTree,
} from '@react-navigation/native';
import { getModalOptions } from './utils';
import { createStackNavigator } from '@react-navigation/stack';
import ModalScreen from './ModalScreen';
import { View } from 'react-native';

const Stack = createStackNavigator();

const WidgetContent: React.FC = ({ route }: any) => {
  const Component = route?.params?.screen;
  return (
    <View
      onLayout={e => {
        route?.params?.setHeight?.(e.nativeEvent.layout.height);
      }}
    >
      <Component />
    </View>
  );
};

const WidgetContainer: React.FC<WidgetContainerProps> = ({
  widget,
  theme = defaultTheme,
  maxApi,
  localize = new Localize({ vi: {}, en: {} }),
}) => {
  const [height, setHeight] = useState<any>(undefined);
  const context = useContext<any>(MiniAppContext);
  const navigationRef = useRef<NavigationContainerRef<any>>(null);
  const isReady = useRef(false);
  const navigator = useRef(new Navigator(navigationRef, isReady, true));
  const [currentContext, setCurrentContext] = useState({});

  let headerBackground = context?.designConfig?.headerBar;
  let headerGradient = theme.colors?.gradient;

  if (theme.assets?.headerBackground) {
    headerBackground = theme.assets?.headerBackground;
  }
  if (context?.designConfig?.headerGradient) {
    headerGradient = context?.designConfig?.headerGradient;
  }

  /**
   * inject data for navigator
   */
  navigator.current.maxApi = maxApi;

  const translate = (data?: string | { vi: string; en: string }) => {
    if (data && typeof data !== 'string') {
      return localize?.translateData(data);
    }
    return localize?.translate(data as string);
  };

  navigator.current.setCurrentContext = setCurrentContext;

  return (
    <View style={{ height: height ?? '100%', minHeight:1 }}>
      <SafeAreaProvider>
        <MiniAppContext.Provider
          value={{
            ...context,
            ...currentContext,
          }}
        >
          <ApplicationContext.Provider
            value={{
              navigator: navigator.current,
              theme: {
                ...theme,
                colors: {
                  ...theme.colors,
                  gradient: headerGradient,
                },
                assets: {
                  ...theme.assets,
                  headerBackground,
                },
              },
              translate,
            }}
          >
            <NavigationIndependentTree>
              <ReactNavigationContainer
                theme={{
                  dark: false,
                  colors: {
                    primary: theme.colors.primary,
                    background: theme.colors.background.default,
                    card: theme.colors.background.surface,
                    text: theme.colors.text.default,
                    border: theme.colors.border.default,
                    notification: theme.colors.error.primary,
                  },
                  fonts: {
                    regular: {
                      fontFamily: 'SFProText',
                      fontWeight: '400',
                    },
                    medium: {
                      fontFamily: 'SFProText',
                      fontWeight: '400',
                    },
                    bold: {
                      fontFamily: 'SFProText',
                      fontWeight: '400',
                    },
                    heavy: {
                      fontFamily: 'SFProText',
                      fontWeight: '400',
                    },
                  },
                }}
                ref={navigationRef}
                onReady={() => {
                  isReady.current = true;
                }}
              >
                <Stack.Navigator
                  initialRouteName="Stack"
                  screenOptions={{
                    headerMode: 'screen',
                  }}
                >
                  <Stack.Screen
                    name="Stack"
                    component={WidgetContent}
                    initialParams={{ screen: widget, setHeight }}
                    options={{
                      headerShown: false,
                    }}
                  />
                  <Stack.Screen
                    name="Modal"
                    component={ModalScreen}
                    options={getModalOptions()}
                    initialParams={{ screen: widget }}
                  />
                </Stack.Navigator>
              </ReactNavigationContainer>
            </NavigationIndependentTree>
          </ApplicationContext.Provider>
        </MiniAppContext.Provider>
      </SafeAreaProvider>
    </View>
  );
};

export { WidgetContainer };
