import { useRef } from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api/client';
import { ProductCard } from '@/components/ProductCard';
import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles';
import type { ProductsResponse } from '@/types/product';

interface ProductCarouselProps {
  id: string;
  title?: string;
  subtitle?: string;
  cta_text?: string;
  cta_url?: string;
  /** 'trending' | 'new' | 'on_sale' | 'featured' — maps to a query param */
  source?: string;
  /** Explicit product IDs to display */
  product_ids?: number[];
  /** Category ID to filter */
  category_id?: number;
  limit?: number;
  styles?: Record<string, any>;
  elementStyles?: Record<string, any>;
}

export function ProductCarousel({
  id,
  title = 'Trending Now',
  subtitle,
  cta_text,
  cta_url,
  source = 'trending',
  product_ids,
  category_id,
  limit = 8,
  styles,
  elementStyles,
}: ProductCarouselProps) {
  const trackRef = useRef<HTMLDivElement>(null);
  const sectionBg = getSectionBackground(styles);

  // Build query params
  const queryParams = new URLSearchParams({ per_page: String(limit) });
  if (product_ids && product_ids.length > 0) {
    queryParams.set('include', product_ids.join(','));
  } else if (category_id) {
    queryParams.set('category', String(category_id));
  } else {
    if (source === 'on_sale') queryParams.set('on_sale', '1');
    if (source === 'featured') queryParams.set('featured', '1');
    if (source === 'new') queryParams.set('orderby', 'date');
    if (source === 'trending') queryParams.set('orderby', 'popularity');
  }

  const { data, isLoading } = useQuery<ProductsResponse>({
    queryKey: ['product-carousel', id, source, product_ids, category_id, limit],
    queryFn: () => apiClient.get<ProductsResponse>(`/shop/products?${queryParams}`),
    staleTime: 5 * 60 * 1000,
  });

  const products = data?.products || [];

  const scroll = (direction: 'left' | 'right') => {
    if (!trackRef.current) return;
    const cardWidth = trackRef.current.children[0]?.clientWidth || 280;
    trackRef.current.scrollBy({ left: direction === 'left' ? -cardWidth * 2 : cardWidth * 2, behavior: 'smooth' });
  };

  return (
    <section id={id} className="wn-section wn-product-carousel py-12 md:py-16" style={sectionBg.style}>
      <div className="container mx-auto px-4 max-w-7xl">
        {/* Header */}
        <div className="flex items-end justify-between mb-8">
          <div>
            {title && (
              <h2
                className="text-3xl md:text-4xl font-bold"
                style={{ color: elementStyles?.title?.color }}
              >
                {title}
              </h2>
            )}
            {subtitle && (
              <p className="text-muted-foreground mt-2" style={{ color: elementStyles?.subtitle?.color }}>
                {subtitle}
              </p>
            )}
          </div>
          <div className="flex items-center gap-3">
            {cta_text && cta_url && (
              <Link to={cta_url} className="text-sm font-semibold hover:underline mr-4 whitespace-nowrap">
                {cta_text} →
              </Link>
            )}
            {/* Arrow buttons */}
            <button
              onClick={() => scroll('left')}
              className="hidden md:flex font-[inherit] w-10 h-10 rounded-full border border-border items-center justify-center hover:bg-muted transition-colors"
              aria-label="Scroll left"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            <button
              onClick={() => scroll('right')}
              className="hidden md:flex font-[inherit] w-10 h-10 rounded-full border border-border items-center justify-center hover:bg-muted transition-colors"
              aria-label="Scroll right"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Scrollable Track */}
        <div
          ref={trackRef}
          className="flex gap-4 overflow-x-auto snap-x snap-mandatory scrollbar-hide pb-2"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          {isLoading
            ? Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="snap-start flex-shrink-0 w-52 md:w-64 animate-pulse">
                  <div className="aspect-square bg-muted rounded-xl mb-3" />
                  <div className="h-4 bg-muted rounded w-3/4 mb-2" />
                  <div className="h-4 bg-muted rounded w-1/2" />
                </div>
              ))
            : products.map((product) => (
                <div key={product.id} className="snap-start flex-shrink-0 w-52 md:w-64">
                  <ProductCard product={product} />
                </div>
              ))}
        </div>
      </div>
    </section>
  );
}
