import Box from '@material-hu/mui/Box';
import { type SxProps, type Theme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { countryCodeToFlagEmoji } from '../utils';

type TeamFlagProps = {
  countryCode?: string | null;
  flagUrl?: string | null;
  name?: string;
  emoji?: string | null;
  size?: number;
  sx?: SxProps<Theme>;
};

const TeamFlag = ({
  countryCode,
  flagUrl,
  name = '',
  emoji: emojiFromBackend,
  size = 32,
  sx,
}: TeamFlagProps) => {
  const emoji = emojiFromBackend || countryCodeToFlagEmoji(countryCode);

  let borderRadius = '6px';
  if (size >= 48) borderRadius = '12px';
  else if (size >= 32) borderRadius = '8px';

  return (
    <Box
      sx={[
        {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: '1px solid',
          borderColor: theme => theme.palette.new.border.neutral.default,
          overflow: 'hidden',
          borderRadius,
          width: size,
          height: size,
        },
        ...(Array.isArray(sx) ? sx : [sx]),
      ]}
    >
      {flagUrl ? (
        <Box
          component="img"
          src={flagUrl}
          alt={name}
          sx={{ width: '100%', height: '100%', objectFit: 'cover' }}
        />
      ) : (
        <Typography sx={{ fontSize: size, lineHeight: 1 }}>
          {emoji || '\u{1F3F3}\u{FE0F}'}
        </Typography>
      )}
    </Box>
  );
};

export default TeamFlag;
