import React, { useCallback, useEffect, useRef } from 'react';
import cn from '@/lib/merge-clsx';
import Icon from '@/components/base/Icon';
import { ScrollbarProps } from './SwiperElement';
import './styles.css';

const Scrollbar: React.FC<ScrollbarProps> = ({ swiperRef, isDragging }) => {
  const thumbRef = useRef<HTMLDivElement>(null);
  const scrollBarRef = useRef<HTMLDivElement>(null);

  const handlePointerDown = () => {
    isDragging.current = false;
  };

  const handlePointerUp = useCallback(() => {
    if (!isDragging.current && swiperRef?.current?.swiper) {
      const { swiper } = swiperRef.current;
      const isLastSlide = swiper.slides.length - 1 === swiper.activeIndex;
      isLastSlide ? swiper.slideTo(0) : swiper.slideNext();
    }
    isDragging.current = false;
  }, [swiperRef, isDragging]);

  // Prevent click event when dragging
  useEffect(() => {
    const thumbElement = thumbRef.current;
    if (!thumbElement) return;

    const handleClick = (e: MouseEvent) => {
      if (isDragging.current) {
        e.preventDefault();
        e.stopPropagation();
      }
    };

    thumbElement.addEventListener('click', handleClick);
    return () => {
      thumbElement.removeEventListener('click', handleClick);
    };
  }, [isDragging]);

  const classNames = cn([
    'border-1',
    'relative',
    'bg-origin-border',
    'border-transparent',
    'bg-[linear-gradient(90deg,#CC93D3_0%,#793BE0_100%)]',
    'w-16 h-16',
    'group',
    'top-1/2',
    'rounded-full',
    'cursor-grab active:cursor-grabbing select-none',
    'before:bg-content',
    'before:absolute',
    'before:inset-0',
    'before:rounded-full',
    'before:bg-black',
    'before:-z-10',
    'data-[hover=true]:!duration-[800ms] ease-in-out',
    'flex items-center justify-center',
    'z-10'
  ]);

  return (
    <div
      ref={scrollBarRef}
      className="swiper-scrollbar-drag !bg-transparent flex items-center justify-center">
      <div className={classNames}>
        <div className="circle-us" />
        <div
          ref={thumbRef}
          onPointerDown={handlePointerDown}
          onPointerUp={handlePointerUp}
          className="text-xl text-white w-16 h-16 flex items-center justify-center rounded-full cursor-pointer isolate z-10 relative"
          role="button"
          aria-label="Adjust slider value">
          <Icon name="forward-arrow" />
        </div>
      </div>
    </div>
  );
};

Scrollbar.displayName = 'Scrollbar';

export default Scrollbar;
