import {Platform, StyleProp, StyleSheet, TextStyle} from 'react-native';

import {GetTextStyleParams, TextWeight, WeightValues} from './interfaces';

// Do not replace this for global "isIos" constant. This is to avoid cycle dependency
const isIos = Platform.OS === 'ios';

/**
 * Get the correct text styles to apply fontWeight and fontStyle in Android and iOS
 */
export const getFontStyle = (
  weight: WeightValues,
  fontStyle?: TextStyle['fontStyle'],
): TextStyle => {
  const fontDecorator = !isIos && fontStyle === 'italic' ? 'Italic' : '';

  switch (weight) {
    case 'light':
    case '300':
      return isIos
        ? {
            fontWeight: TextWeight.light,
            fontStyle: fontStyle,
          }
        : {
            fontFamily: `Roboto-Light${fontDecorator}`,
          };
    case 'bold':
    case '700':
      return isIos
        ? {
            fontWeight: TextWeight.bold,
            fontStyle: isIos ? fontStyle : undefined,
          }
        : {
            fontFamily: `Roboto-Bold${fontDecorator}`,
          };
    case 'medium':
    case '500':
      return isIos
        ? {
            fontWeight: TextWeight.medium,
            fontStyle: isIos ? fontStyle : undefined,
          }
        : {
            fontFamily: `Roboto-Medium${fontDecorator}`,
          };
    case 'regular':
    case '400':
    default:
      return isIos
        ? {
            fontWeight: TextWeight.regular,
            fontStyle: isIos ? fontStyle : undefined,
          }
        : {
            fontFamily: fontDecorator ? 'Roboto-Italic' : 'Roboto-Regular',
          };
  }
};

export const getTextStyles = ({
  style,
  weight,
  fontStyle,
}: GetTextStyleParams): StyleProp<TextStyle> => {
  const flattenStyle = StyleSheet.flatten(style);
  const fontWeight = flattenStyle?.fontWeight || weight;
  const targetFontStyle = flattenStyle?.fontStyle || fontStyle;

  return [
    flattenStyle,
    getFontStyle(fontWeight as WeightValues, targetFontStyle),
  ];
};
