import React, { useContext, memo } from 'react';
import { ContextRegions } from '../../contexts';
import { SBox } from '../../../common/s-components/layout/s-box';
import { Skeleton } from './skeleton';
import { fp as _ } from '../../../common/utils/fp';
import { RegionPill } from './region-pill';
import { TRegion } from '../../../track-nmf/types';
import { FETCH_TYPE } from '../../../common/constants';
import { onNmfRegionOpen, onHhRegionOpen } from '../../../analytics';
import { MagneticCarousel } from '../../../common/components/magnetic-carousel';

export const Regions = memo(() => {
  const props = useContext(ContextRegions);

  const {
    visibilitySettings,
    settings,
    config,
    setConfig,
    getData,
    pageVariant,
  } = props;
  const regions = _.path('data.regions', settings) as TRegion[];
  const activeRegion = _.path('region', config) as string;
  const isNmf = pageVariant === 'nmf';

  return (
    <SBox mb={28}>
      {visibilitySettings.skeleton ? <Skeleton /> : null}
      {visibilitySettings.data ? (
        <MagneticCarousel
          testID="nmf-regions"
          outerGap={16}
          innerGap={12}
          keyId="code"
          data={regions}
          renderItem={(item, key, onPress) => {
            return (
              <RegionPill
                region={item}
                active={activeRegion === item.code}
                onPress={() => {
                  if (onPress) {
                    onPress();
                  }
                  setConfig({ region: item.code });
                  getData(null, FETCH_TYPE.filter);
                  if (isNmf) {
                    onNmfRegionOpen({ nmfRegionSelected: item.name });
                  } else {
                    onHhRegionOpen({ hhRegionSelected: item.name });
                  }
                }}
              />
            );
          }}
        />
      ) : null}
    </SBox>
  );
});
