import React, { useCallback, useEffect, useState } from 'react';
import { DotFilledIcon } from '@radix-ui/react-icons';
import { Flex } from '../atoms/flex';

export interface DotNavigationProps {
  /** 전체 점 갯수 */
  dotCount?: number;
  /** 점 클릭 시 */
  onClick?: (index: number) => void;
  /** 현재 선택된 점 */
  dotIndex?: number;
  /** 기본 점 위치 */
  defaultDotIndex?: number;
  /** 선택된 점 변경 시 실행 */
  onChangeDotIndex?: (index: number) => void;
}

export function DotNavigation(props: DotNavigationProps): React.ReactElement {
  const { dotCount, onClick, dotIndex, defaultDotIndex, onChangeDotIndex } =
    props;

  const [currentDot, setCurrentDot] = useState<number>(
    () => defaultDotIndex ?? dotIndex ?? 0
  );

  const onClickDot = useCallback(
    (i: number) => {
      if (onClick) {
        onClick(i);
      } else {
        setCurrentDot(i);
      }
    },
    [onClick]
  );

  useEffect(() => {
    onChangeDotIndex?.(currentDot);
  }, [currentDot, onChangeDotIndex]);

  useEffect(() => {
    if (typeof dotIndex === 'undefined') return;
    setCurrentDot(dotIndex);
  }, [dotIndex]);

  return (
    <Flex>
      {dotCount
        ? Array.from({ length: dotCount }, (_, i) => i).map((_, index) => {
            const isSelected = currentDot === index;
            return (
              <DotFilledIcon
                height="24px"
                // eslint-disable-next-line react/no-array-index-key -- index외의 키가 없음
                key={index}
                onClick={() => {
                  onClickDot(index);
                }}
                opacity={isSelected ? undefined : 0.25}
                style={{
                  cursor: 'pointer',
                }}
                width="24px"
              />
            );
          })
        : null}
    </Flex>
  );
}
