import * as React from 'react';
import { classNames, hasReactNode } from '@vkontakte/vkjs';
import type { HTMLAttributesWithRootRef } from '../../types';
import {
  HorizontalScroll,
  type HorizontalScrollProps,
  type ScrollPositionHandler,
} from '../HorizontalScroll/HorizontalScroll';
import { RootComponent } from '../RootComponent/RootComponent';
import styles from './SubnavigationBar.module.css';

export interface SubnavigationBarProps
  extends HTMLAttributesWithRootRef<HTMLDivElement>,
    Pick<
      HorizontalScrollProps,
      | 'showArrows'
      | 'arrowSize'
      | 'getScrollToLeft'
      | 'getScrollToRight'
      | 'scrollAnimationDuration'
    > {
  /**
   * Отключение возможности прокручивания компонента по горизонтали.
   */
  fixed?: boolean;
  /**
   * Отключает отступы. Рекомендуется использовать с `mode="outline"` у [`SubnavigationButton`](https://vkui.io/components/subnavigation-button).
   */
  noPadding?: boolean;
}

const defaultScrollToLeft: ScrollPositionHandler = (x) => x - 240;

const defaultScrollToRight: ScrollPositionHandler = (x) => x + 240;

/**
 * @see https://vkui.io/components/subnavigation-bar
 */
export const SubnavigationBar = ({
  fixed = false,
  children,
  showArrows = true,
  noPadding = false,
  arrowSize = 's',
  getScrollToLeft = defaultScrollToLeft,
  getScrollToRight = defaultScrollToRight,
  scrollAnimationDuration,
  ...restProps
}: SubnavigationBarProps): React.ReactNode => {
  let ScrollWrapper: React.ElementType;
  let scrollWrapperProps = {};

  if (fixed) {
    ScrollWrapper = 'div';
  } else {
    ScrollWrapper = HorizontalScroll;
    scrollWrapperProps = {
      showArrows,
      arrowSize,
      getScrollToLeft,
      getScrollToRight,
      scrollAnimationDuration,
    };
  }

  return (
    <RootComponent baseClassName={fixed && styles.modeFixed} {...restProps}>
      <ScrollWrapper className={styles.in} {...scrollWrapperProps}>
        <ul className={classNames(styles.scrollIn, noPadding && styles.noPadding)}>
          {React.Children.map(children, (child, idx) =>
            hasReactNode(child) ? (
              <li key={idx} className={styles.item}>
                {child}
              </li>
            ) : null,
          )}
        </ul>
      </ScrollWrapper>
    </RootComponent>
  );
};
