import React, { useEffect, useRef, useState } from 'react';
import { Box, HStack, IconButton, Heading, useColorModeValue } from '@chakra-ui/react';
import { ChevronLeftIcon, ChevronRightIcon } from '@chakra-ui/icons';
import { useClubTheme } from '../../contexts/ClubThemeContext';

interface HorizontalScrollerProps {
  title?: string;
  rightAction?: React.ReactNode;
  children: React.ReactNode;
  // Enhancements (all optional; defaults keep legacy behavior)
  draggable?: boolean; // enable mouse/touch drag scrolling
  autoScroll?: boolean; // enable continuous auto-scroll
  autoSpeed?: number; // pixels per frame (~60fps). default 1.2
  rewindLoop?: boolean; // if true, jump to start when reaching end (instead of stopping)
  pauseOnHover?: boolean; // pause auto-scroll on hover
  infiniteScroll?: boolean; // duplicate children for seamless infinite loop
}

const SCROLL_AMOUNT = 0.7; // 70% of viewport width per click

const HorizontalScroller: React.FC<HorizontalScrollerProps> = ({ title, rightAction, children, draggable = false, autoScroll = false, autoSpeed = 1.2, rewindLoop = true, pauseOnHover = true, infiniteScroll = false }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const theme = useClubTheme();
  const cardBg = useColorModeValue('white', 'gray.800');
  const [isHovering, setIsHovering] = useState(false);
  const isPointerDownRef = useRef(false);
  const startXRef = useRef(0);
  const startScrollLeftRef = useRef(0);
  const hasDraggedRef = useRef(false);
  const rafIdRef = useRef<number | null>(null);

  const scrollBy = (dir: 1 | -1) => {
    const el = containerRef.current;
    if (!el) return;
    // Use the container width rather than window width for more accurate scrolling
    const amount = Math.floor(el.clientWidth * SCROLL_AMOUNT) * dir;
    el.scrollBy({ left: amount, behavior: 'smooth' });
  };

  // Mouse/touch drag handlers
  const onPointerDown = (clientX: number) => {
    const el = containerRef.current;
    if (!el) return;
    isPointerDownRef.current = true;
    hasDraggedRef.current = false;
    startXRef.current = clientX;
    startScrollLeftRef.current = el.scrollLeft;
    // while dragging, disable smooth scroll behavior and selection
    el.style.scrollSnapType = 'none';
    el.style.cursor = 'grabbing';
    (document.body as any).style.userSelect = 'none';
  };
  const onPointerMove = (clientX: number) => {
    const el = containerRef.current;
    if (!el || !isPointerDownRef.current) return;
    const dx = clientX - startXRef.current;
    if (Math.abs(dx) > 3) hasDraggedRef.current = true;
    el.scrollLeft = startScrollLeftRef.current - dx;
  };
  const onPointerUp = () => {
    const el = containerRef.current;
    isPointerDownRef.current = false;
    if (el) {
      el.style.cursor = 'grab';
    }
    (document.body as any).style.userSelect = '';
    if (el) {
      // restore snap a moment later for a natural feel
      setTimeout(() => { if (el) el.style.scrollSnapType = 'x mandatory'; }, 100);
    }
  };

  // Auto-scroll implementation with infinite scroll support
  useEffect(() => {
    const el = containerRef.current;
    if (!autoScroll || !el) return;

    // For infinite scroll, set initial position to middle of duplicated content
    if (infiniteScroll) {
      const halfWidth = el.scrollWidth / 2;
      el.scrollLeft = halfWidth;
    }

    let running = true;
    const step = () => {
      if (!running || !el) return;
      
      const scrollLeft = el.scrollLeft;
      const scrollWidth = el.scrollWidth;
      const clientWidth = el.clientWidth;
      
      const shouldPause = (pauseOnHover && isHovering) || isPointerDownRef.current;
      
      if (!shouldPause) {
        if (infiniteScroll) {
          // Seamless infinite loop by resetting when reaching halfway
          const halfWidth = scrollWidth / 2;
          if (scrollLeft >= halfWidth) {
            el.scrollLeft = 0;
          } else {
            el.scrollLeft += autoSpeed;
          }
        } else {
          // Original rewind behavior
          const atEnd = scrollLeft + clientWidth >= scrollWidth - 2;
          if (atEnd && rewindLoop) {
            el.scrollLeft = 0;
          } else if (!atEnd) {
            el.scrollLeft += autoSpeed;
          }
        }
      }
      
      rafIdRef.current = requestAnimationFrame(step);
    };
    
    // Start the animation loop
    rafIdRef.current = requestAnimationFrame(step);
    
    return () => {
      running = false;
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
    };
  }, [autoScroll, autoSpeed, pauseOnHover, isHovering, rewindLoop, infiniteScroll]);

  return (
    <Box position="relative">
      {(title || rightAction) && (
        <HStack justify="space-between" mb={3}>
          {title && (
            <Heading size="lg" letterSpacing="0.04em" style={{ textTransform: 'uppercase' }}>
              {title}
            </Heading>
          )}
          {rightAction}
        </HStack>
      )}

      {/* gradient masks for fancy edges */}
      <Box
        pointerEvents="none"
        position="absolute"
        left={0}
        top={0}
        bottom={0}
        w={{ base: 16, md: 24 }}
        bgGradient={useColorModeValue(
          'linear(to-r, white, rgba(255,255,255,0.9), rgba(255,255,255,0.4), transparent)',
          'linear(to-r, gray.900, rgba(17,25,40,0.9), rgba(17,25,40,0.4), transparent)'
        )}
        zIndex={1}
      />
      <Box
        pointerEvents="none"
        position="absolute"
        right={0}
        top={0}
        bottom={0}
        w={{ base: 16, md: 24 }}
        bgGradient={useColorModeValue(
          'linear(to-l, white, rgba(255,255,255,0.9), rgba(255,255,255,0.4), transparent)',
          'linear(to-l, gray.900, rgba(17,25,40,0.9), rgba(17,25,40,0.4), transparent)'
        )}
        zIndex={1}
      />

      {/* scroll area */}
      <HStack
        ref={containerRef}
        spacing={4}
        overflowX="auto"
        py={2}
        px={1}
        cursor={draggable ? 'grab' : 'default'}
        onMouseEnter={() => setIsHovering(true)}
        onMouseLeave={() => { setIsHovering(false); if (draggable) onPointerUp(); }}
        onMouseDown={(e) => { if (!draggable) return; e.preventDefault(); onPointerDown(e.clientX); }}
        onMouseMove={(e) => { if (!draggable) return; onPointerMove(e.clientX); }}
        onMouseUp={() => { if (!draggable) return; onPointerUp(); }}
        onTouchStart={(e) => { if (!draggable) return; if (e.touches[0]) onPointerDown(e.touches[0].clientX); }}
        onTouchMove={(e) => { if (!draggable) return; if (e.touches[0]) onPointerMove(e.touches[0].clientX); }}
        onTouchEnd={() => { if (!draggable) return; onPointerUp(); }}
        css={{
          scrollSnapType: infiniteScroll ? 'none' : 'x proximity',
          scrollBehavior: 'smooth',
          WebkitOverflowScrolling: 'touch',
          '&::-webkit-scrollbar': {
            height: '6px',
          },
          '&::-webkit-scrollbar-track': {
            background: 'transparent',
          },
          '&::-webkit-scrollbar-thumb': {
            background: useColorModeValue('rgba(0,0,0,0.15)', 'rgba(255,255,255,0.15)'),
            borderRadius: '3px',
          },
          '&::-webkit-scrollbar-thumb:hover': {
            background: useColorModeValue('rgba(0,0,0,0.25)', 'rgba(255,255,255,0.25)'),
          },
        }}
      >
        {children}
        {infiniteScroll && children}
      </HStack>

      {/* navigation buttons - must be above gradient masks */}
      <IconButton
        aria-label="scroll left"
        icon={<ChevronLeftIcon boxSize={6} />}
        onClick={(e) => { 
          e.preventDefault(); 
          e.stopPropagation(); 
          scrollBy(-1); 
        }}
        onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); }}
        onTouchStart={(e) => { e.preventDefault(); e.stopPropagation(); }}
        position="absolute"
        top="50%"
        transform="translateY(-50%)"
        left={{ base: 1, md: 2 }}
        size="lg"
        colorScheme="blackAlpha"
        bg={useColorModeValue('rgba(255,255,255,0.95)', 'rgba(45,55,72,0.95)')}
        color={useColorModeValue('gray.800', 'white')}
        boxShadow="xl"
        _hover={{ bg: useColorModeValue('white', 'gray.600'), transform: 'translateY(-50%) scale(1.15)', boxShadow: '2xl' }}
        _active={{ transform: 'translateY(-50%) scale(0.95)' }}
        transition="all 0.2s"
        zIndex={30}
        borderRadius="full"
        pointerEvents="auto"
      />
      <IconButton
        aria-label="scroll right"
        icon={<ChevronRightIcon boxSize={6} />}
        onClick={(e) => { 
          e.preventDefault(); 
          e.stopPropagation(); 
          scrollBy(1); 
        }}
        onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); }}
        onTouchStart={(e) => { e.preventDefault(); e.stopPropagation(); }}
        position="absolute"
        top="50%"
        transform="translateY(-50%)"
        right={{ base: 1, md: 2 }}
        size="lg"
        colorScheme="blackAlpha"
        bg={useColorModeValue('rgba(255,255,255,0.95)', 'rgba(45,55,72,0.95)')}
        color={useColorModeValue('gray.800', 'white')}
        boxShadow="xl"
        _hover={{ bg: useColorModeValue('white', 'gray.600'), transform: 'translateY(-50%) scale(1.15)', boxShadow: '2xl' }}
        _active={{ transform: 'translateY(-50%) scale(0.95)' }}
        transition="all 0.2s"
        zIndex={30}
        borderRadius="full"
        pointerEvents="auto"
      />

      {/* bottom accent line */}
      <Box mt={2} h="2px" bg={theme.primary} borderRadius="full" />
    </Box>
  );
};

export default HorizontalScroller;
