import { useCallback, useState } from 'react';
import dynamic from 'next/dynamic';

import type { ClickableOnClick } from '~/src/components/Clickable';
import type { PageSectionComponent } from '../types';
import type { ReleasesSectionProps } from './types';

import Box from '~/src/components/Box';
import getPublicEndpoint from '~/src/lib/getPublicEndpoint';
import { useRegisterNavItem } from '../../components/ItemPageNav';
import { usePageTheme } from '../../hooks/theme';
import HorizontalItemsSection from '../lib/HorizontalItemsSection';
import useOpenLink from '../lib/useOpenLink';
import { MAX_ITEMS } from './constants';
import { useResolveAlbums } from './utils';

const PagePeekDynamic = dynamic(() => import('../lib/PagePeek'), {
  ssr: false,
});

const ReleasesSection: PageSectionComponent<ReleasesSectionProps> = ({
  title,
  albums,
  albumIds = albums?.map(({ id }) => id).slice(0, MAX_ITEMS) ?? [],
  sectionId,
  sectionIndex,
  pagePeeking,
  navTitle,
}) => {
  const items = useResolveAlbums({ albumIds, albums });
  const [pagePeekPath, setPagePeekPath] = useState<string>();
  const openLink = useOpenLink();
  const pageTheme = usePageTheme();

  useRegisterNavItem({
    id: sectionId,
    text: navTitle,
    index: sectionIndex,
    skip: !items?.length,
  });

  const onItemClick = useCallback<
    ClickableOnClick<{ url: string; name: string }>
  >(({ event, data: { url, name } }) => {
    event.preventDefault();

    openLink({
      url,
      onPagePeek: setPagePeekPath,
      pagePeeking,
      name,
    });
  }, []);

  if (!items) {
    return null;
  }

  return (
    <Box testId="releases">
      <HorizontalItemsSection
        title={title}
        backgroundColor={pageTheme.backgroundColor}
        items={items.map(({ name, image, id, pagePath }) => {
          const url = new URL(pagePath, getPublicEndpoint()).toString();

          return {
            key: id,
            image,
            // use the full url to ensure links work under CustomDomain
            href: url,
            text: name,
            testId: 'releasesItem',
            textLineClamp: 1,

            onClick: onItemClick,
            data: {
              url,
              name,
            },
          };
        })}
      />
      {pagePeekPath && (
        <PagePeekDynamic
          pagePath={pagePeekPath}
          onClose={() => {
            setPagePeekPath(undefined);
          }}
        />
      )}
    </Box>
  );
};

export default ReleasesSection;
