import React, { memo, useCallback, useState } from 'react';
import { SBox } from '../../common/s-components/layout/s-box';
import { theme } from '../../app/theme';
import { Icon } from '../../common/components/icon';
import { Touchable } from '../../common/components/touchable';
import { SImage } from '../../common/s-components/s-image';
import { getFlagSource } from '../../common/transducers';
import { SText } from '../../common/s-components/typography/s-text';
import { fp as _ } from '../../common/utils/fp';
import { TSetActive } from '../types';

type TProps = {
  value?: string;
  onClose?: TSetActive;
};

export const MarketTag: React.FC<TProps> = memo(props => {
  const { onClose, value } = props;
  const [pressed, setPressed] = useState(false);

  const renderCircle = () => {
    return (
      <SBox
        testID="empty-market-tag"
        width={32}
        height={32}
        bg={theme.colors.ebonyClay}
        borderRadius={16}
      />
    );
  };

  const renderFlag = useCallback(() => {
    const sourceFlag = getFlagSource(value!, 'small', 'light');
    return (
      <SBox position="absolute" opacity={pressed ? 0.7 : 1}>
        <SImage source={sourceFlag} width={16} height={16} />
      </SBox>
    );
  }, [value]);

  const renderClose = useCallback(() => {
    return (
      <>
        <SBox width={18} height={18} position="absolute" top={0} right={-5}>
          <SBox
            width={18}
            height={18}
            bg={theme.colors.ebonyClay}
            borderRadius={16}
            alignItems="center"
            justifyContent="center"
          >
            <Icon
              name="cross"
              color={theme.colors.lavenderGray}
              size={12}
              opacity={pressed ? 0.7 : 1}
            />
          </SBox>
        </SBox>
        <SBox width={44} height={44} position="absolute" top={0} left={-6}>
          <Touchable
            onPress={() => onClose!(value!)}
            onPressIn={() => {
              setPressed(true);
            }}
            onPressOut={() => {
              setPressed(false);
            }}
            testID="market-tag"
          >
            <SBox width={44} height={44} />
          </Touchable>
        </SBox>
      </>
    );
  }, [onClose, value]);

  const renderLabel = useCallback(() => {
    const marketCode = value === '_gl' ? 'gl' : value;
    return (
      <SBox mt={3} alignItems="center">
        <SText fontSize={12}>{_.toUpperSafe(marketCode)}</SText>
      </SBox>
    );
  }, [value]);

  return (
    <SBox pt={6}>
      {value ? (
        <>
          <SBox alignItems="center" justifyContent="center">
            {renderCircle()}
            {renderFlag()}
          </SBox>
          {renderClose()}
          {renderLabel()}
        </>
      ) : (
        renderCircle()
      )}
    </SBox>
  );
});

MarketTag.defaultProps = {
  onClose: () => {},
};
