import React, { useContext, memo } from 'react';
import { Portal } from '../../../common/utils/portal/portal';
import { SwipeablePopup } from '../../../common/components/bottom-sheet/swipeable-popup';
import { POPUP_INFO_ID, SINGLE_VARIANT } from '../../constants';
import { InfoPopup } from './info-popup';
import { InfoTitle } from '../../../common/components/info-title';
import { togglePopup } from '../../../common/utils/swipeable-popup-service';
// import { CLICK_SOURCES, onInfoIconPress } from '../../../analytics';
import { ContextHeader } from '../../contexts';
import { TContextHeader } from '../../types';
import { Skeleton } from './skeleton';
import { SRow } from '../../../common/s-components/layout/s-row';
import { SH6 } from '../../../common/s-components/typography/s-h6';
import { formatYearDate } from '../../../common/transducers';
import { CLICK_SOURCES, onInfoIconPress } from '../../../analytics';

export const Header = memo(() => {
  const props: TContextHeader = useContext(ContextHeader);
  const { visibility, refresh, dateRange, youtubeVariant } = props;
  const { skeleton, error, empty } = visibility;
  const showSkeleton = skeleton && !refresh;
  const { start_date, end_date } = dateRange;
  const dateRangeTitle = `${formatYearDate(start_date)}–${formatYearDate(
    end_date
  )}`;

  const infoPressHandler = (variant: string) => {
    togglePopup(variant);
    onInfoIconPress({
      source_section:
        youtubeVariant === SINGLE_VARIANT
          ? CLICK_SOURCES.YT_MARKETS
          : CLICK_SOURCES.YT_MARKETS_ALL,
    });
  };

  const renderFgLayer = () => {
    return (
      <>
        <Portal id="youtube-markets:header">
          <SwipeablePopup variant={POPUP_INFO_ID} content={<InfoPopup />} />
        </Portal>
      </>
    );
  };

  if (showSkeleton) return <Skeleton />;
  return (
    <>
      {!showSkeleton ? (
        <>
          {renderFgLayer()}
          <SRow justifyContent="space-between" px={16} mb={20}>
            <InfoTitle
              testID="info-title-youtube-performance"
              onPress={() => {
                infoPressHandler(POPUP_INFO_ID);
              }}
              title="Markets"
            />
            {!(error || empty) ? (
              <SH6 mt={8} color="periwinkleGray">
                {dateRangeTitle}
              </SH6>
            ) : null}
          </SRow>
        </>
      ) : null}
    </>
  );
});
