import { useLayoutEffect } from 'react';
import { useColorScheme } from 'react-native';
import type { StatusBarProps } from './types';
import { toStatusBarContentStyle } from './utils';
import { useInitialProps } from '../initial-props';
import { useNavigation } from '../router/BedrockRoute';

export function StatusBar(props: StatusBarProps) {
  useStatusBar(props);

  return null;
}

export function useStatusBar({ style, hidden }: StatusBarProps) {
  const { initialColorPreference } = useInitialProps();
  const navigation = useNavigation();
  const colorPreference = useColorScheme();

  useLayoutEffect(() => {
    let statusBarStyle: 'light' | 'dark';

    switch (toStatusBarContentStyle(style, colorPreference ?? initialColorPreference)) {
      case 'light-content':
        statusBarStyle = 'light';
        break;
      case 'dark-content':
        statusBarStyle = 'dark';
        break;
    }

    navigation.setOptions({
      statusBarStyle,
      statusBarHidden: hidden,
    });
  }, [navigation, initialColorPreference, colorPreference, style, hidden]);
}
