import { renderBlock } from '../../BlockRenderer/renderBlock';
import { renderChildren } from '../../BlockRenderer/renderChildren';
import { type BlockDef } from '../../model/ContentPageDef';
import { type UniBlockProps } from '../../UniBlock/UniBlockProps';
import { getBorderStyle } from '../../utils/getBorderStyle';
import { style } from '../../utils/style';
import { type CardSizeMode } from './CarouselContent';
import { renderCardHighlight } from './renderCardHighlight';

const cardBaseStyle = 'relative h-full';

const CARD_SIZE_MAP: Record<CardSizeMode, string> = {
  small: 'lg:min-w-64',
  normal: 'lg:min-w-80 xl:min-w-96',
  big: 'lg:min-w-[515px]',
};

export const renderCarouselCards = ({
  noCardBorder,
  cardSize = 'normal',
  isNavButtons = false,
  isMobile = false,
  ...rest
}: UniBlockProps & {
  noCardBorder?: boolean;
  cardSize?: CardSizeMode;
  isNavButtons?: boolean;
  isMobile?: boolean;
}) => {
  const { blocks: childBlocks } = rest.block || {};
  const someCardsHighlighted = childBlocks?.some(isCardHighlighted);
  const defaultPadding = isNavButtons ? { defaultPadding: 'p-6xl pb-m' } : {};

  return renderChildren({
    ...rest,
    renderProps: ({ block, options, i }) => (
      <div key={String(i)} className={cardWrapperStyle(block, { someCardsHighlighted })}>
        {renderBlock({
          block,
          options,
          extra: {
            className: cardStyle(block, {
              someCardsHighlighted,
              showBorder: !noCardBorder,
              cardSize,
            }),
            ...defaultPadding,
            i,
          },
          isMobile,
        })}
        {isCardHighlighted(block)
          ? renderCardHighlight({ className: 'absolute top-0 -right-4 z-40' })
          : null}
      </div>
    ),
  });
};

const cardWrapperStyle = (
  _: BlockDef | undefined,
  { someCardsHighlighted }: { someCardsHighlighted?: boolean },
) => style(cardBaseStyle, someCardsHighlighted && (isCardHighlighted(_) ? 'pt-3xl' : 'pt-16'));

const cardStyle = (
  _: BlockDef | undefined,
  {
    someCardsHighlighted,
    showBorder,
    cardSize = 'normal',
  }: { someCardsHighlighted?: boolean; showBorder?: boolean; cardSize?: CardSizeMode },
) =>
  style(
    cardBaseStyle,
    'min-w-80',
    CARD_SIZE_MAP[cardSize], // TODO fix для RecommendationCard
    someCardsHighlighted && (isCardHighlighted(_) ? 'pt-16' : 'pt-3xl'),
    getBorderStyle(showBorder),
    showBorder && 'h-full',
  );

const isCardHighlighted = (_: BlockDef | undefined) =>
  _?.content && 'isHighlighting' in _.content && _.content.isHighlighting;
