import React, { useRef, useState, useEffect, useCallback } from 'react';

interface DoubleImageDisplayProps {
  imageUrls: string[];
  title: string;
  themeColor: string;
}

// 滚动条状态管理
interface ScrollbarState {
  isDragging: boolean;
  scrollPosition: number;
}

// 滚动条交互工具函数
const createScrollbarInteraction = (
  containerRef: React.RefObject<HTMLDivElement | null>,
  scrollState: ScrollbarState,
  setScrollState: React.Dispatch<React.SetStateAction<ScrollbarState>>
) => {
  const handleScrollbarClick = (event: React.MouseEvent) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const clickPosition = event.clientX - rect.left;
    const scrollPercentage = clickPosition / rect.width;

    if (containerRef.current) {
      const scrollWidth = containerRef.current.scrollWidth - containerRef.current.clientWidth;
      containerRef.current.scrollLeft = scrollWidth * scrollPercentage;
    }
  };

  const handleScrollbarDragStart = (event: React.MouseEvent) => {
    event.preventDefault();
    setScrollState(prev => ({ ...prev, isDragging: true }));
  };

  const handleScrollbarDrag = (event: React.MouseEvent) => {
    if (!scrollState.isDragging) return;

    const rect = event.currentTarget.getBoundingClientRect();
    const dragPosition = event.clientX - rect.left;
    const scrollPercentage = Math.max(0, Math.min(1, dragPosition / rect.width));

    if (containerRef.current) {
      const scrollWidth = containerRef.current.scrollWidth - containerRef.current.clientWidth;
      containerRef.current.scrollLeft = scrollWidth * scrollPercentage;
    }
  };

  const handleScrollbarDragEnd = () => {
    setScrollState(prev => ({ ...prev, isDragging: false }));
  };

  return {
    handleScrollbarClick,
    handleScrollbarDragStart,
    handleScrollbarDrag,
    handleScrollbarDragEnd
  };
};

const DoubleImageDisplay: React.FC<DoubleImageDisplayProps> = ({ imageUrls, title, themeColor }) => {
  const imageContainerRef = useRef<HTMLDivElement>(null);
  const [scrollState, setScrollState] = useState<ScrollbarState>({
    isDragging: false,
    scrollPosition: 0
  });

  const {
    handleScrollbarClick,
    handleScrollbarDragStart,
    handleScrollbarDrag,
    handleScrollbarDragEnd
  } = createScrollbarInteraction(imageContainerRef, scrollState, setScrollState);

  const syncScrollbarPosition = useCallback(() => {
    if (imageContainerRef.current) {
      const scrollLeft = imageContainerRef.current.scrollLeft;
      const scrollWidth = imageContainerRef.current.scrollWidth - imageContainerRef.current.clientWidth;
      const scrollPercentage = scrollWidth > 0 ? scrollLeft / scrollWidth : 0;

      setScrollState(prev => ({
        ...prev,
        scrollPosition: scrollPercentage
      }));
    }
  }, []);

  useEffect(() => {
    const container = imageContainerRef.current;
    if (!container) return;

    const handleScroll = () => {
      syncScrollbarPosition();
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [syncScrollbarPosition]);

  useEffect(() => {
    if (imageContainerRef.current) {
      syncScrollbarPosition();
    }
  }, [imageUrls, syncScrollbarPosition]);

  return (
    <>
      <div
        ref={imageContainerRef}
        data-layer="双图滚动容器"
        className="flex overflow-x-auto gap-[20px] h-full items-center"
        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
      >
        {/* 第一张图片 - 宽度853px */}
        <div
          data-layer="图片1"
          className="h-[640px] overflow-clip relative rounded-[10px] shrink-0 w-[853px]"
        >
          <img
            data-layer={`${title} 1`}
            className="w-full h-full object-cover"
            src={imageUrls[0]}
            alt={`${title} 1`}
          />
        </div>
        {/* 第二张图片 - 宽度940px */}
        <div
          data-layer="图片2"
          className="h-[640px] overflow-clip relative rounded-[10px] shrink-0 w-[940px]"
        >
          <img
            data-layer={`${title} 2`}
            className="w-full h-full object-cover"
            src={imageUrls[1]}
            alt={`${title} 2`}
          />
        </div>
      </div>

      {/* 自定义滚动条 - 双图模式专用 */}
      <div
        data-layer="滚动条容器"
        className="absolute bottom-[-40px] left-1/2 transform -translate-x-1/2 w-[60%] h-[8px] bg-stone-700/30 rounded-[4px] cursor-pointer"
        onClick={handleScrollbarClick}
        onMouseDown={handleScrollbarDragStart}
        onMouseMove={scrollState.isDragging ? handleScrollbarDrag : undefined}
        onMouseUp={handleScrollbarDragEnd}
        onMouseLeave={handleScrollbarDragEnd}
      >
        <div
          data-layer="滚动条滑块"
          className="absolute h-full bg-stone-400 rounded-[4px] transition-all duration-200 hover:bg-stone-300 cursor-grab active:cursor-grabbing"
          style={{
            width: '20%',
            left: `${scrollState.scrollPosition * 80}%`,
            backgroundColor: themeColor
          }}
        />
      </div>
    </>
  );
};

export default DoubleImageDisplay;