import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import ProductImage from './ProductImage';
import { isVariantAvailable, type VariantKind } from '../lib/variantStock';

interface ProductVariant {
  id: number;
  name: string;
  volume: string;
  volumeMl: number;
  currentPrice: number;
  kind?: VariantKind;
  stock?: number;
}

interface ProductBadge {
  name: string;
  color?: string | null;
}

interface Product {
  id: number;
  slug: string;
  name: string;
  description: string;
  brandName: string;
  primaryImage: string;
  stock: number;
  badges?: ProductBadge[];
  variants: ProductVariant[];
}

interface TopProductsSectionProps {
  initialProducts?: Product[];
}

const money = (price: number) => new Intl.NumberFormat('cs-CZ', {
  style: 'currency',
  currency: 'CZK',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
}).format(price);

const TopProductsSection: React.FC<TopProductsSectionProps> = ({ initialProducts }) => {
  const [products, setProducts] = useState<Product[]>(initialProducts || []);
  const [loading, setLoading] = useState(!initialProducts);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (initialProducts) {
      setProducts(initialProducts);
      setLoading(false);
      return;
    }

    const fetchProducts = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/top-products');
        if (!response.ok) throw new Error('Failed to fetch products');
        setProducts(await response.json());
        setError(null);
      } catch {
        setError('Nepodařilo se načíst nejoblíbenější produkty.');
      } finally {
        setLoading(false);
      }
    };

    void fetchProducts();
  }, [initialProducts]);

  const scrollToCollection = () => {
    document.querySelector('[data-section="all-products"]')?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  };

  if (loading) {
    return (
      <section className="w-full bg-[#0d0d0d] px-4 py-16 sm:px-6 lg:px-[5vw] lg:py-20">
        <div className="mx-auto max-w-[1120px] animate-pulse">
          <div className="mb-10 h-11 w-72 bg-white/[0.06]" />
          {[0, 1, 2].map((item) => (
            <div key={item} className="grid grid-cols-[32px_74px_1fr] gap-3 border-b border-white/10 py-4 sm:grid-cols-[48px_96px_1fr_110px_158px] sm:gap-5">
              <div className="h-8 bg-white/[0.04]" />
              <div className="aspect-[2/3] bg-white/[0.06]" />
              <div className="h-16 bg-white/[0.04]" />
            </div>
          ))}
        </div>
      </section>
    );
  }

  if (error || products.length === 0) {
    return (
      <section className="w-full bg-[#0d0d0d] px-4 py-16 text-center sm:px-6">
        <p className="text-sm text-luxury-light/55">
          {error || 'Nejoblíbenější produkty právě připravujeme.'}
        </p>
      </section>
    );
  }

  const rankedProducts = products.slice(0, 3).map((product, index) => {
    const availableVariants = product.variants.filter((variant) => isVariantAvailable(variant, product.stock));
    const pricePool = availableVariants.length ? availableVariants : product.variants;
    const fromPrice = pricePool.length
      ? Math.min(...pricePool.map((variant) => Number(variant.currentPrice)))
      : 0;
    const availableCount = availableVariants.length;
    const stockVariantLabel = availableCount === 1
      ? 'varianta skladem'
      : availableCount >= 2 && availableCount <= 4
        ? 'varianty skladem'
        : 'variant skladem';
    const catalogVariantLabel = availableCount === 1
      ? 'dostupná varianta'
      : availableCount >= 2 && availableCount <= 4
        ? 'dostupné varianty'
        : 'dostupných variant';

    return {
      product,
      index,
      fromPrice,
      availableCount,
      stockVariantLabel,
      catalogVariantLabel,
      isWinner: index === 0,
    };
  });

  return (
    <section className="w-full border-y border-white/10 bg-[#0d0d0d] px-4 py-16 sm:px-6 lg:px-[5vw] lg:py-20" aria-labelledby="top-products-title">
      <div className="mx-auto max-w-[1120px]">
        <header className="mb-8 flex items-end justify-between gap-6 sm:mb-10">
          <div>
            <p className="mb-2 text-[11px] font-bold uppercase tracking-[0.2em] text-luxury-gold sm:text-xs">Žebříček zákazníků</p>
            <h2 id="top-products-title" className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl">
              Nejprodávanější vůně
            </h2>
          </div>
          <button
            type="button"
            onClick={scrollToCollection}
            className="group hidden items-center gap-2 border-b border-luxury-light/35 pb-1 text-xs text-luxury-light/60 transition-colors hover:border-luxury-gold hover:text-luxury-gold sm:flex"
          >
            Celá kolekce
            <ArrowIcon className="transition-transform group-hover:translate-x-0.5" />
          </button>
        </header>

        <div className="border-t border-white/10 md:hidden">
          {rankedProducts.map(({ product, index, fromPrice, availableCount, stockVariantLabel, isWinner }) => (
            <article
              key={product.id}
              className={`group relative grid min-w-0 grid-cols-[32px_74px_minmax(0,1fr)_44px] items-center gap-3 border-b px-2 py-4 transition-colors sm:grid-cols-[48px_96px_minmax(0,1fr)_110px_158px] sm:gap-5 sm:px-4 sm:py-5 ${
                isWinner
                  ? 'border-luxury-gold/25 bg-gradient-to-r from-luxury-gold/[0.08] via-luxury-gold/[0.025] to-transparent'
                  : 'border-white/10 hover:bg-white/[0.025]'
              }`}
            >
              <span className={`text-xl font-black tracking-[-0.04em] sm:text-2xl ${isWinner ? 'text-luxury-gold' : 'text-luxury-light/25'}`}>
                {String(index + 1).padStart(2, '0')}
              </span>

              <Link href={`/product/${product.slug}`} className="relative block aspect-[2/3] overflow-hidden bg-luxury-dark" aria-label={`Zobrazit ${product.name}`}>
                {product.badges?.[0] && (
                  <span
                    className="absolute left-1.5 top-1.5 z-10 max-w-[calc(100%-12px)] px-1.5 py-1 text-[7px] font-bold uppercase tracking-[0.08em] sm:left-2 sm:top-2 sm:px-2 sm:text-[8px]"
                    style={{ backgroundColor: product.badges[0].color || 'rgba(255,255,255,.92)', color: product.badges[0].color ? '#fff' : '#141414' }}
                  >
                    {product.badges[0].name}
                  </span>
                )}
                <ProductImage src={product.primaryImage} alt={product.name} priority={index === 0} className="h-full w-full object-cover transition-transform duration-500 ease-out group-hover:scale-[1.03]" />
              </Link>

              <div className="min-w-0">
                <p className="mb-1 text-[9px] font-semibold uppercase tracking-[0.13em] text-luxury-light/40 sm:text-[10px]">{product.brandName}</p>
                <h3 className="truncate text-sm font-semibold leading-tight text-luxury-light sm:text-lg">
                  <Link href={`/product/${product.slug}`} className="transition-colors hover:text-luxury-gold">{product.name}</Link>
                </h3>
                <p className="mt-1.5 text-[9px] text-luxury-light/40 sm:text-[11px]">{availableCount} {stockVariantLabel}</p>
                <p className="mt-2 text-[13px] font-bold text-luxury-gold sm:hidden">od {money(fromPrice)}</p>
              </div>

              <div className="hidden text-right sm:block">
                <p className="text-[9px] uppercase tracking-[0.12em] text-luxury-light/35">Cena od</p>
                <p className="mt-1 whitespace-nowrap text-base font-bold text-luxury-gold">{money(fromPrice)}</p>
              </div>

              <Link
                href={`/product/${product.slug}`}
                aria-label={`Zobrazit produkt ${product.name}`}
                className={`flex h-11 w-11 items-center justify-center justify-self-end text-xs font-bold transition-all sm:min-h-12 sm:w-full sm:gap-2 sm:px-3 ${
                  isWinner
                    ? 'bg-luxury-gold text-luxury-dark hover:bg-[#f3bd35]'
                    : 'border border-white/20 text-luxury-light hover:border-luxury-gold hover:bg-luxury-gold hover:text-luxury-dark'
                }`}
              >
                <span className="hidden sm:inline">Zobrazit produkt</span>
                <ArrowIcon />
              </Link>
            </article>
          ))}
        </div>

        <div className="mx-auto hidden max-w-[900px] grid-cols-3 gap-x-[18px] md:grid">
          {rankedProducts.map(({ product, index, fromPrice, availableCount, catalogVariantLabel }) => (
            <article key={product.id} className="group relative min-w-0">
              <span className="absolute right-3 top-3 z-20 grid h-10 w-10 place-items-center rounded-full border border-white/15 bg-black/55 text-[11px] font-bold tracking-[0.08em] text-white shadow-lg backdrop-blur-sm">
                {String(index + 1).padStart(2, '0')}
              </span>

              <div className="relative overflow-hidden bg-[#0d0d0d]">
                <Link href={`/product/${product.slug}`} className="relative block aspect-[2/3] overflow-hidden" aria-label={`Zobrazit ${product.name}`}>
                  {product.badges && product.badges.length > 0 && (
                    <span className="absolute left-3 top-3 z-10 flex max-w-[calc(100%-68px)] flex-wrap gap-1.5">
                      {product.badges.map((badge, badgeIndex) => (
                        <span
                          key={`${badge.name}-${badgeIndex}`}
                          className="px-2.5 py-1.5 text-[9px] font-bold uppercase tracking-[0.09em]"
                          style={{ backgroundColor: badge.color || 'rgba(255,255,255,.92)', color: badge.color ? '#fff' : '#141414' }}
                        >
                          {badge.name}
                        </span>
                      ))}
                    </span>
                  )}
                  <ProductImage src={product.primaryImage} alt={product.name} priority={index === 0} className="h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.025]" />
                </Link>

                <Link href={`/product/${product.slug}`} className="absolute bottom-3 left-3 right-3 flex min-h-12 translate-y-16 items-center justify-between bg-white/95 px-4 text-xs font-bold text-[#151515] transition-all duration-300 hover:bg-luxury-gold group-hover:translate-y-0"><span>Zobrazit produkt</span><ArrowIcon /></Link>
              </div>

              <div className="px-px pt-4">
                <p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-luxury-light/45">{product.brandName}</p>
                <h3 className="my-1.5 min-h-[2.5em] text-sm font-semibold leading-[1.25] text-luxury-light sm:text-[15px]">
                  <Link href={`/product/${product.slug}`} className="hover:text-luxury-gold">{product.name}</Link>
                </h3>
                <div className="flex items-baseline justify-between gap-2">
                  <p className="whitespace-nowrap text-[13px] font-bold text-luxury-gold sm:text-sm">od {money(fromPrice)}</p>
                  <p className="text-right text-[10px] text-luxury-light/45 sm:text-[11px]">{availableCount} {catalogVariantLabel}</p>
                </div>
              </div>
            </article>
          ))}
        </div>

        <button
          type="button"
          onClick={scrollToCollection}
          className="mt-8 flex min-h-12 w-full items-center justify-center gap-2 border border-white/20 px-4 text-xs font-bold uppercase tracking-[0.1em] text-luxury-light sm:hidden"
        >
          Zobrazit celou kolekci
          <ArrowIcon />
        </button>
      </div>
    </section>
  );
};

function ArrowIcon({ className = '' }: { className?: string }) {
  return <svg className={`h-4 w-4 ${className}`} fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M5 12h14m-5-5 5 5-5 5" /></svg>;
}

export default TopProductsSection;
