'use client';

import { useState, useRef } from 'react';
import type { CrossSelling } from '@/lib/shopware-api';
import ProductCard from '@/components/product/ProductCard';

interface ProductCrossSellingProps {
  crossSellings: CrossSelling[];
}

export default function ProductCrossSelling({ crossSellings }: ProductCrossSellingProps) {
  const activeCrossSellings = crossSellings.filter(
    (cs) => cs.crossSelling.active && cs.products.length > 0
  );
  const [activeIndex, setActiveIndex] = useState(0);

  if (activeCrossSellings.length === 0) return null;

  const current = activeCrossSellings[activeIndex];

  return (
    <div className="mt-12">
      {/* Tab-style headers like Shopware */}
      <div className="border-b border-surface-200 mb-6">
        <div className="flex gap-6">
          {activeCrossSellings.map((cs, i) => {
            const name = cs.crossSelling.translated?.name || cs.crossSelling.name;
            return (
              <button
                key={cs.crossSelling.id}
                onClick={() => setActiveIndex(i)}
                className={`pb-3 text-base font-medium transition-colors relative ${
                  activeIndex === i
                    ? 'text-brand-600'
                    : 'text-surface-400 hover:text-surface-600'
                }`}
              >
                {name}
                {activeIndex === i && (
                  <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-brand-600" />
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Product slider */}
      <CrossSellingSlider key={current.crossSelling.id} crossSelling={current} />
    </div>
  );
}

function CrossSellingSlider({ crossSelling }: { crossSelling: CrossSelling }) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);

  const updateScrollState = () => {
    const el = scrollRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 0);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);
  };

  const scroll = (direction: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;
    const amount = el.clientWidth * 0.75;
    el.scrollBy({ left: direction === 'left' ? -amount : amount, behavior: 'smooth' });
  };

  const showArrows = crossSelling.products.length > 4;

  return (
    <div className="relative">
      {/* Scroll arrows */}
      {showArrows && (
        <>
          <button
            onClick={() => scroll('left')}
            disabled={!canScrollLeft}
            className="absolute -left-4 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white border border-surface-200 rounded-full shadow-sm flex items-center justify-center hover:border-surface-300 disabled:opacity-0 transition-all"
            aria-label="Scroll left"
          >
            <svg className="w-5 h-5 text-surface-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <button
            onClick={() => scroll('right')}
            disabled={!canScrollRight}
            className="absolute -right-4 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white border border-surface-200 rounded-full shadow-sm flex items-center justify-center hover:border-surface-300 disabled:opacity-0 transition-all"
            aria-label="Scroll right"
          >
            <svg className="w-5 h-5 text-surface-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </>
      )}

      <div
        ref={scrollRef}
        onScroll={updateScrollState}
        className="flex gap-4 overflow-x-auto pb-2 snap-x snap-mandatory scrollbar-hide"
      >
        {crossSelling.products.map((product) => (
          <div key={product.id} className="snap-start flex-none w-56 sm:w-64">
            <ProductCard product={product} />
          </div>
        ))}
      </div>
    </div>
  );
}
