import React, { useRef } from 'react';
import { Platform } from 'react-native';
import { SImage } from '../s-components/s-image';
import { getMarketCode, getFlagSource } from '../transducers';
import { SBox } from '../s-components/layout/s-box';
import { withMarkets } from '../hoc/with-markets';

type TProps = {
  market?: string;
  // TODO: remove width and height use size instead
  // TODO: remove width and height use size instead
  // TODO: remove width and height use size instead
  width?: number;
  height?: number;
  marginTop?: number;
  // mt?: number;
  variant?: 'default' | 'light' | 'white';
  // TODO: use number instead of 'small' and 'big' - get image by measuring this number
  // TODO: use number instead of 'small' and 'big' - get image by measuring this number
  // TODO: use number instead of 'small' and 'big' - get image by measuring this number
  size?: 'small' | 'big';
  inlineFlag?: boolean;
};

const FlagComponent: React.FC<TProps> = props => {
  const { market, width, height, marginTop, variant, size, inlineFlag } = props;
  const marketCode = getMarketCode(market);
  // cont sizeForGetFlagSource = size < 40 ? 'small' : 'big'
  const sourceFlag = getFlagSource(marketCode, size!, variant!);
  const isAndroid = Platform.OS === 'android';
  const bg = useRef();

  const toggleLoading = () => {
    // @ts-ignore
    bg.current.setNativeProps({
      style: {
        opacity: 0,
      },
    });
  };

  return (
    <>
      {inlineFlag && isAndroid ? (
        <SImage
          marginTop={marginTop}
          source={sourceFlag}
          width={width}
          height={height}
          backgroundColor="eastBay"
          borderRadius={width! / 2}
          resizeMode="contain"
        />
      ) : (
        <SBox position="relative" width={width} height={height} mt={marginTop}>
          <SBox
            bg="eastBay"
            width={width}
            height={height}
            borderRadius={width! / 2}
            ref={bg}
            position="absolute"
          />
          <SImage
            source={sourceFlag}
            width={width}
            height={height}
            onLoadEnd={toggleLoading}
          />
        </SBox>
      )}
    </>
  );
};

FlagComponent.defaultProps = {
  width: 44,
  height: 44,
  // TODO refactor should be zero by default!!!
  // TODO refactor should be zero by default!!!
  // TODO refactor should be zero by default!!!
  marginTop: 10,
  variant: 'default',
  size: 'small',
  inlineFlag: false,
};

export const Flag = withMarkets(FlagComponent) as any;
