import React from 'react';
import {
  ImageStyle,
  StyleProp,
  StyleSheet,
  TextStyle,
  View,
  ViewStyle,
} from 'react-native';
import * as Flags3x2 from 'country-flag-icons/string/3x2';
import {SvgXml} from 'react-native-svg';
import {Image, Typography} from '@components';
import {EMOJI_SIZE} from '@modules/prodev2/constants';
import {countryCodeToFlagEmoji} from '@modules/prodev2/utils';

import {styles} from './styles';

const FLAG_ASPECT_RATIO = 1.5;

export interface TeamFlagProps {
  emoji?: Nullable<string>;
  countryCode?: Nullable<string>;
  flagUrl?: Nullable<string>;
  name: string;
  emojiSize?: number;
  containerStyle?: StyleProp<ViewStyle>;
  imageStyle?: StyleProp<ImageStyle>;
  emojiStyle?: StyleProp<TextStyle>;
}

export function TeamFlag({
  emoji,
  countryCode,
  flagUrl,
  name,
  emojiSize = EMOJI_SIZE,
  containerStyle,
  imageStyle,
  emojiStyle,
}: TeamFlagProps) {
  const isoCode = countryCode?.toUpperCase();
  const boxStyle = imageStyle as StyleProp<ViewStyle>;

  if (flagUrl) {
    return (
      <View style={[styles.box, containerStyle, boxStyle]}>
        <Image
          source={{uri: flagUrl}}
          accessibilityLabel={name}
          contentFit="cover"
          style={imageStyle}
        />
      </View>
    );
  }

  if (isoCode && isoCode in Flags3x2) {
    const flat = (StyleSheet.flatten(imageStyle) ?? {}) as ImageStyle;
    const boxHeight = typeof flat.height === 'number' ? flat.height : emojiSize;
    return (
      <View style={[styles.box, containerStyle, boxStyle]}>
        <SvgXml
          xml={Flags3x2[isoCode as keyof typeof Flags3x2]}
          style={{height: boxHeight, width: boxHeight * FLAG_ASPECT_RATIO}}
        />
      </View>
    );
  }

  const fallbackEmoji = emoji || countryCodeToFlagEmoji(countryCode) || '🏳️';
  return (
    <View style={[styles.center, containerStyle]}>
      <Typography
        align="center"
        style={[{fontSize: emojiSize, lineHeight: emojiSize}, emojiStyle]}>
        {fallbackEmoji}
      </Typography>
    </View>
  );
}

export default TeamFlag;
