import { useMemo } from 'react';

import type { HorizontalItemsSectionProps } from '../lib/HorizontalItemsSection';
import type { PageSectionComponent } from '../types';
import type { MerchSectionProps } from './types';

import Box from '~/src/components/Box';
import { useSelector } from '~/src/store/redux';
import { selectUserCountry } from '~/src/store/session/selectors';
import { useRegisterNavItem } from '../../components/ItemPageNav';
import { usePageTheme } from '../../hooks/theme';
import HorizontalItemsSection from '../lib/HorizontalItemsSection';
import { MerchText } from './utils';

const MerchSection: PageSectionComponent<MerchSectionProps> = ({
  title,
  navTitle,
  sectionId,
  sectionIndex,
  items = [],
  territoryOverrides,
}) => {
  useRegisterNavItem({
    id: sectionId,
    text: navTitle,
    index: sectionIndex,
  });

  const pageTheme = usePageTheme();
  const userCountry = useSelector(selectUserCountry);

  const displayItems = territoryOverrides?.[userCountry]?.items || items;
  const displayTitle = territoryOverrides?.[userCountry]?.title || title;

  return (
    <Box testId="merch">
      <HorizontalItemsSection
        title={displayTitle}
        backgroundColor={pageTheme.backgroundColor}
        items={useMemo<HorizontalItemsSectionProps['items']>(() => {
          return displayItems.map(
            ({ name, link, image, price, priceCurrency }) => {
              return {
                key: link,
                image,
                href: link,
                testId: 'merchListItem',
                title: name,

                imageStyle: {
                  margin: '1rem',
                },

                text: (
                  <MerchText
                    name={name}
                    price={price}
                    priceCurrency={priceCurrency}
                  />
                ),
              };
            }
          );
        }, [displayItems])}
      />
    </Box>
  );
};

export default MerchSection;
