import React, { useState, useRef, useEffect } from 'react';
import { Box, IconButton, Flex, Heading, Link as ChakraLink } from '@chakra-ui/react';
import { FiChevronLeft, FiChevronRight, FiArrowRight } from 'react-icons/fi';
import '../../styles/sparta-styles.css';

interface Article {
  id: string;
  title: string;
  slug: string;
  image: string;
  categories: string[];
  date: string;
  duration?: string;
  isVideo?: boolean;
  unlimited?: boolean;
}

interface SpartaHorizontalSliderProps {
  title: string;
  titleLink?: string;
  articles: Article[];
  itemsPerView?: {
    mobile: number;
    tablet: number;
    desktop: number;
  };
  gap?: number;
  showControls?: boolean;
  enableDrag?: boolean;
  showUnlimitedBadge?: boolean;
  showCategories?: boolean;
  showDuration?: boolean;
}

const SpartaHorizontalSlider: React.FC<SpartaHorizontalSliderProps> = ({
  title,
  titleLink = '#',
  articles,
  itemsPerView = { mobile: 1, tablet: 2, desktop: 3 },
  gap = 16,
  showControls = true,
  enableDrag = true,
  showUnlimitedBadge = true,
  showCategories = true,
  showDuration = true,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);
  const trackRef = useRef<HTMLDivElement>(null);

  // Calculate how many items are visible based on viewport
  const getItemsPerView = () => {
    if (typeof window === 'undefined') return itemsPerView.desktop;
    
    const width = window.innerWidth;
    if (width < 768) return itemsPerView.mobile;
    if (width < 1024) return itemsPerView.tablet;
    return itemsPerView.desktop;
  };

  const [visibleItems, setVisibleItems] = useState(getItemsPerView());

  useEffect(() => {
    const handleResize = () => {
      setVisibleItems(getItemsPerView());
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const maxIndex = Math.max(0, articles.length - visibleItems);
  const canGoNext = currentIndex < maxIndex;
  const canGoPrev = currentIndex > 0;

  const handleNext = () => {
    if (canGoNext) {
      setCurrentIndex(prev => Math.min(prev + 1, maxIndex));
    }
  };

  const handlePrev = () => {
    if (canGoPrev) {
      setCurrentIndex(prev => Math.max(prev - 1, 0));
    }
  };

  // Drag functionality
  const handleMouseDown = (e: React.MouseEvent) => {
    if (!enableDrag || !trackRef.current) return;
    setIsDragging(true);
    setStartX(e.pageX - trackRef.current.offsetLeft);
    setScrollLeft(trackRef.current.scrollLeft);
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !trackRef.current) return;
    e.preventDefault();
    const x = e.pageX - trackRef.current.offsetLeft;
    const walk = (x - startX) * 2;
    trackRef.current.scrollLeft = scrollLeft - walk;
  };

  // Calculate transform based on current index
  const slideWidth = trackRef.current?.children[0]?.clientWidth || 0;
  const transformValue = -(currentIndex * (slideWidth + gap));

  return (
    <Box className="sparta-slider-container sparta-container sparta-section">
      {/* Header with title and controls */}
      <Flex className="sparta-slider-header" justifyContent="space-between" alignItems="center" mb={4}>
        <Heading className="sparta-slider-title" as="h2">
          <ChakraLink href={titleLink} display="inline-flex" alignItems="center" gap={2}>
            {title}
            <Box as={FiArrowRight} />
          </ChakraLink>
        </Heading>

        {showControls && (
          <Flex className="sparta-slider-controls" gap={2}>
            <IconButton
              aria-label="Previous"
              icon={<FiChevronLeft />}
              onClick={handlePrev}
              isDisabled={!canGoPrev}
              className="sparta-slider-button"
              variant="ghost"
            />
            <IconButton
              aria-label="Next"
              icon={<FiChevronRight />}
              onClick={handleNext}
              isDisabled={!canGoNext}
              className="sparta-slider-button"
              variant="ghost"
            />
          </Flex>
        )}
      </Flex>

      {/* Slider viewport */}
      <Box className="sparta-slider-viewport" overflow="hidden">
        <Flex
          ref={trackRef}
          className="sparta-slider-track"
          gap={`${gap}px`}
          transition="transform 0.3s cubic-bezier(0.4, 0, 0.6, 1)"
          transform={`translate3d(${transformValue}px, 0, 0)`}
          cursor={enableDrag ? (isDragging ? 'grabbing' : 'grab') : 'default'}
          onMouseDown={handleMouseDown}
          onMouseUp={handleMouseUp}
          onMouseMove={handleMouseMove}
          onMouseLeave={handleMouseUp}
        >
          {articles.map((article) => (
            <Box
              key={article.id}
              className="sparta-slider-slide"
              flexShrink={0}
              data-dragging={isDragging}
            >
              <ChakraLink
                href={`/articles/${article.slug}`}
                className="sparta-article-card"
                textDecoration="none"
                _hover={{ textDecoration: 'none' }}
              >
                {/* Article Image */}
                <Box className="sparta-article-image" position="relative">
                  <img
                    src={article.image}
                    alt={article.title}
                    loading="lazy"
                    draggable={false}
                  />

                  {/* Meta info overlay */}
                  {(showUnlimitedBadge && article.unlimited) && (
                    <Box className="sparta-article-meta">
                      <Box className="sparta-article-badge">
                        UNLIMITED
                      </Box>
                    </Box>
                  )}

                  {/* Video duration */}
                  {showDuration && article.duration && (
                    <Box
                      position="absolute"
                      bottom="8px"
                      right="8px"
                      padding="4px 8px"
                      background="rgba(0, 0, 0, 0.8)"
                      borderRadius="4px"
                      fontSize="0.75rem"
                      fontWeight="500"
                    >
                      {article.duration}
                    </Box>
                  )}
                </Box>

                {/* Article Details */}
                <Box className="sparta-article-details">
                  {showCategories && article.categories.length > 0 && (
                    <Flex className="sparta-article-categories">
                      {article.categories.map((cat, idx) => (
                        <React.Fragment key={idx}>
                          <span>{cat}</span>
                          {idx < article.categories.length - 1 && (
                            <Box className="sparta-hero-separator" />
                          )}
                        </React.Fragment>
                      ))}
                    </Flex>
                  )}

                  <Heading className="sparta-article-title" as="h3" size="sm">
                    {article.title}
                  </Heading>

                  <Box className="sparta-article-date" mt="auto">
                    {new Date(article.date).toLocaleDateString('cs-CZ', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric',
                    })}
                  </Box>
                </Box>
              </ChakraLink>
            </Box>
          ))}
        </Flex>
      </Box>
    </Box>
  );
};

export default SpartaHorizontalSlider;

// Example usage:
/*
<SpartaHorizontalSlider
  title="Videa"
  titleLink="/sparta-tv"
  articles={[
    {
      id: '1',
      title: 'HIGHLIGHTS: Sparta - Slavia',
      slug: 'highlights-sparta-slavia',
      image: 'https://example.com/image.jpg',
      categories: ['Match content', 'Highlights'],
      date: '2025-10-05',
      duration: '4:32',
      isVideo: true,
      unlimited: true,
    },
    // ... more articles
  ]}
  itemsPerView={{ mobile: 1, tablet: 2, desktop: 3 }}
  showUnlimitedBadge={true}
  showCategories={true}
  showDuration={true}
/>
*/
