import React, { useEffect, useState, useRef } from 'react';
import Link from 'next/link';

interface Brand {
  id: number;
  name: string;
  slug: string;
  description: string;
  website?: string;
  image_url?: string;
}

const BrandSpotlight: React.FC = () => {
  const [brands, setBrands] = useState<Brand[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);

  useEffect(() => {
    const fetchBrands = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/brands');
        if (!response.ok) {
          throw new Error('Failed to fetch brands');
        }
        const data = await response.json();
        setBrands(data);
        setError(null);
      } catch (err) {
        setError('Nepodařilo se načíst značky');
        setBrands([]);
      } finally {
        setLoading(false);
      }
    };

    fetchBrands();
  }, []);

  useEffect(() => {
    const checkScroll = () => {
      if (scrollContainerRef.current) {
        const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current;
        setCanScrollLeft(scrollLeft > 0);
        setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
      }
    };

    checkScroll();
    const container = scrollContainerRef.current;
    if (container) {
      container.addEventListener('scroll', checkScroll);
      window.addEventListener('resize', checkScroll);
      return () => {
        container.removeEventListener('scroll', checkScroll);
        window.removeEventListener('resize', checkScroll);
      };
    }
  }, [brands]);

  const scroll = (direction: 'left' | 'right') => {
    if (scrollContainerRef.current) {
      const itemWidth = scrollContainerRef.current.querySelector('div')?.offsetWidth || 0;
      const scrollAmount = itemWidth + 16; // item width + gap
      scrollContainerRef.current.scrollBy({
        left: direction === 'left' ? -scrollAmount : scrollAmount,
        behavior: 'smooth',
      });
    }
  };

  // Filter brands that have images
  const brandsWithImages = brands.filter((brand) => brand.image_url);

  return (
    <section className="w-full bg-luxury-dark py-8 sm:py-10 md:py-16">
      <div className="max-w-7xl mx-auto px-3 sm:px-4 md:px-6 lg:px-8">
        {/* Section Header */}
        <div className="text-center mb-6 sm:mb-8 md:mb-12">
          <p className="text-luxury-gold text-xs sm:text-sm md:text-base font-semibold uppercase tracking-wider mb-1.5 sm:mb-2">
            Poznáme značky
          </p>
          <h2 className="text-2xl sm:text-3xl md:text-5xl lg:text-6xl font-aptos font-black text-luxury-light mb-3 sm:mb-4">
            Prémiové Značky
          </h2>
          <div className="w-10 sm:w-12 h-1 bg-luxury-gold mx-auto" />
        </div>

        {/* Loading State */}
        {loading && (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-luxury-gold"></div>
          </div>
        )}

        {/* Error State */}
        {error && !loading && (
          <div className="bg-red-500/10 border border-red-500/30 text-red-400 p-4 rounded-lg text-center mb-6">
            {error}
          </div>
        )}

        {/* Brands Images Carousel */}
        {!loading && brandsWithImages.length > 0 && (
          <div className="relative group">
            {/* Navigation Buttons */}
            <button
              onClick={() => scroll('left')}
              className={`absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1 sm:-translate-x-3 md:-translate-x-6 lg:-translate-x-8 z-10 w-8 h-8 sm:w-9 sm:h-9 md:w-10 md:h-10 flex items-center justify-center rounded-full transition-all duration-300 ${
                canScrollLeft
                  ? 'bg-luxury-gold text-luxury-dark hover:bg-yellow-300 opacity-100'
                  : 'bg-luxury-gold/30 text-luxury-dark opacity-50 cursor-not-allowed'
              }`}
              disabled={!canScrollLeft}
              aria-label="Posunout vlevo"
            >
              <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
                  clipRule="evenodd"
                />
              </svg>
            </button>

            <button
              onClick={() => scroll('right')}
              className={`absolute right-0 top-1/2 -translate-y-1/2 translate-x-1 sm:translate-x-3 md:translate-x-6 lg:translate-x-8 z-10 w-8 h-8 sm:w-9 sm:h-9 md:w-10 md:h-10 flex items-center justify-center rounded-full transition-all duration-300 ${
                canScrollRight
                  ? 'bg-luxury-gold text-luxury-dark hover:bg-yellow-300 opacity-100'
                  : 'bg-luxury-gold/30 text-luxury-dark opacity-50 cursor-not-allowed'
              }`}
              disabled={!canScrollRight}
              aria-label="Posunout vpravo"
            >
              <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
                  clipRule="evenodd"
                />
              </svg>
            </button>

            {/* Scroll Container - 4 items visible */}
            <div
              ref={scrollContainerRef}
              className="flex gap-4 overflow-x-auto pb-2"
              style={{
                scrollBehavior: 'smooth',
                msOverflowStyle: 'none',
                scrollbarWidth: 'none',
              }}
            >
              <style>{`
                div::-webkit-scrollbar {
                  display: none;
                }
              `}</style>

              {brandsWithImages.map((brand) => (
                <Link
                  key={brand.id}
                  href={`/brands/${brand.slug}`}
                  className="flex-shrink-0 w-1/2 sm:w-1/3 md:w-1/4 aspect-square group relative overflow-hidden rounded-lg hover:shadow-lg hover:shadow-luxury-gold/30 transition-all duration-300 cursor-pointer"
                >
                  <img
                    src={brand.image_url!}
                    alt={brand.name}
                    className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                    title={brand.name}
                  />

                  {/* Overlay on Hover */}
                  <div className="absolute inset-0 bg-luxury-dark/60 opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-center justify-center">
                    <p className="text-luxury-light font-aptos font-bold text-center px-2 text-sm md:text-base">
                      {brand.name}
                    </p>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Empty State */}
        {!loading && brandsWithImages.length === 0 && !error && (
          <div className="text-center text-luxury-light/60 py-12">
            <p>Žádné značky s obrázky nejsou dostupné</p>
          </div>
        )}
      </div>
    </section>
  );
};

export default BrandSpotlight;
