import { useLayoutEffect } from 'react';
import { StatusBar as BaseStatusBar } from 'react-native';
import type { StatusBarProps } from './types';
import { toStatusBarContentStyle } from './utils';
import { useInitialProps } from '../initial-props';

export function StatusBar({ style, animated, hidden, backgroundColor, translucent = true }: StatusBarProps) {
  const { initialColorPreference } = useInitialProps();
  const translucentWithNoBackgroundColor = translucent && backgroundColor == null;

  return (
    <BaseStatusBar
      translucent={translucent}
      barStyle={toStatusBarContentStyle(style, initialColorPreference)}
      backgroundColor={translucentWithNoBackgroundColor ? 'transparent' : backgroundColor}
      animated={animated}
      hidden={hidden}
    />
  );
}

export function useStatusBar({ style, animated, hidden, backgroundColor, translucent = true }: StatusBarProps) {
  const { initialColorPreference } = useInitialProps();
  const translucentWithNoBackgroundColor = translucent && backgroundColor == null;

  useLayoutEffect(() => {
    BaseStatusBar.setTranslucent(translucent);
    BaseStatusBar.setBarStyle(toStatusBarContentStyle(style, initialColorPreference));
    BaseStatusBar.setBackgroundColor(
      translucentWithNoBackgroundColor ? 'transparent' : (backgroundColor ?? 'transparent')
    );

    if (hidden !== undefined) {
      BaseStatusBar.setHidden(hidden);
    }
  }, [initialColorPreference, translucentWithNoBackgroundColor, style, animated, hidden, backgroundColor, translucent]);
}
