import { BUNDLES_ENABLED } from '@/lib/features';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { GetServerSideProps } from 'next';
import Link from 'next/link';
import { useCart } from '../context/CartContext';
import toast from 'react-hot-toast';
import Seo from '../components/Seo';
import Breadcrumbs, { breadcrumbsJsonLd } from '../components/Breadcrumbs';
import { SITE_URL } from '../lib/seo';
import { fetchFromApi } from '../lib/serverFetch';

interface BundleProduct {
  id: number;
  variantId: number;
  slug: string;
  name: string;
  brandName: string;
  image: string;
  volume: string;
  volumeMl: number;
  price: number;
  productStock: number;
}

interface BundleVariant {
  id: number;
  name: string;
  currentPrice: number;
  originalPrice: number;
  volumeMl?: number;
  products?: BundleProduct[];
}

interface Bundle {
  id: number;
  slug: string;
  name: string;
  image: string;
  products: BundleProduct[];
  currentPrice: number;
  originalPrice: number;
  bundleProductId?: number;
  bundleVariantId?: number;
  variants?: BundleVariant[];
}

const isBundleVariantAvailable = (variant: BundleVariant) =>
  Boolean(variant.products?.length) &&
  variant.products!.every((product) => product.productStock >= product.volumeMl);

function getInitialVariants(data: Bundle[]) {
  const initialVariants: { [bundleId: number]: number } = {};
  data.forEach((bundle) => {
    if (bundle.variants && bundle.variants.length > 0) {
      initialVariants[bundle.id] = (bundle.variants.find(isBundleVariantAvailable) || bundle.variants[0]).id;
    }
  });
  return initialVariants;
}

const formatBundleCount = (count: number) =>
  `${count} ${count === 1 ? 'sada' : count >= 2 && count <= 4 ? 'sady' : 'sad'}`;

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

interface BundlesPageProps {
  initialBundles: Bundle[];
}

const BundlesPage: React.FC<BundlesPageProps> = ({ initialBundles }) => {
  const router = useRouter();
  const { addItem } = useCart();
  const [bundles, setBundles] = useState<Bundle[]>(initialBundles);
  const [loading, setLoading] = useState(initialBundles.length === 0);
  const [error, setError] = useState<string | null>(null);
  const [addedToCart, setAddedToCart] = useState<{ [key: number]: boolean }>({});
  const [selectedVariants, setSelectedVariants] = useState<{ [bundleId: number]: number }>(() =>
    getInitialVariants(initialBundles)
  );

  useEffect(() => {
    if (initialBundles.length > 0) {
      setBundles(initialBundles);
      setSelectedVariants(getInitialVariants(initialBundles));
      setLoading(false);
      return;
    }

    const fetchBundles = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/bundles');
        if (!response.ok) {
          throw new Error('Failed to fetch bundles');
        }
        const data: Bundle[] = await response.json();
        setBundles(data);
        setSelectedVariants(getInitialVariants(data));
        setError(null);
      } catch (err) {
        setError('Nepodařilo se načíst výhodné sady');
      } finally {
        setLoading(false);
      }
    };

    fetchBundles();
  }, [initialBundles]);

  const isBundleAvailable = (bundle: Bundle): boolean => {
    const variant = getSelectedVariant(bundle);
    const products = variant.products || bundle.products;
    return products.length > 0 && products.every((product) => product.productStock >= product.volumeMl);
  };

  const getUnavailableProducts = (bundle: Bundle): BundleProduct[] => {
    const variant = getSelectedVariant(bundle);
    const products = variant.products || bundle.products;
    return products.filter((product) => product.productStock < product.volumeMl);
  };

  const getSelectedVariant = (bundle: Bundle) => {
    if (!bundle.variants || bundle.variants.length === 0) {
      return { currentPrice: bundle.currentPrice, originalPrice: bundle.originalPrice, products: bundle.products };
    }
    const variantId = selectedVariants[bundle.id];
    const variant = bundle.variants.find(v => v.id === variantId) || bundle.variants[0];
    return variant;
  };

  const getVariantProductsForDisplay = (bundle: Bundle) => {
    const variant = getSelectedVariant(bundle);
    return variant.products || bundle.products;
  };

  const handleAddBundleToCart = async (bundle: Bundle) => {
    if (bundle.products.length === 0) {
      toast.error('Sada je prázdná');
      return;
    }

    if (!isBundleAvailable(bundle)) {
      const unavailable = getUnavailableProducts(bundle);
      const names = unavailable.map((p) => p.name).join(', ');
      toast.error(`Nedostupné produkty: ${names}`);
      return;
    }

    const variantId = bundle.variants && bundle.variants.length > 0 
      ? selectedVariants[bundle.id] || bundle.variants[0].id 
      : bundle.bundleVariantId;

    if (!variantId) {
      toast.error('Sada nemá variantu');
      return;
    }

    try {
      await addItem({
        variantId: variantId,
        productId: bundle.bundleProductId!,
        productName: bundle.name,
        productSlug: '', // Bundles don't have a direct slug
        brandName: 'Bundle',
        volume: `${bundle.products.length} ks`,
        price: getSelectedVariant(bundle).currentPrice,
        image: bundle.image,
        productType: 'bundle',
      });

      setAddedToCart((prev) => ({ ...prev, [bundle.id]: true }));
      setTimeout(() => {
        setAddedToCart((prev) => ({ ...prev, [bundle.id]: false }));
      }, 2000);
    } catch (error) {
      toast.error('Chyba při přidávání do košíku');
    }
  };

  if (loading) {
    return (
      <>
        <Seo
          title="Výhodné sady parfémů | Vystříkejto.cz"
          description="Vyberte si výhodné sady parfémů a ušetřete na nákupu originálních vůní."
          canonical={`${SITE_URL}/vyhodne-sady`}
        />
        <div className="w-full bg-luxury-dark min-h-screen flex items-center justify-center pt-40">
          <div className="text-center">
            <div className="inline-block">
              <div className="w-12 h-12 border-4 border-luxury-gold border-t-transparent rounded-full animate-spin" />
            </div>
            <p className="text-luxury-light/70 text-lg mt-4">Načítání sad...</p>
          </div>
        </div>
      </>
    );
  }

  if (error) {
    return (
      <>
        <Seo
          title="Výhodné sady parfémů | Vystříkejto.cz"
          description="Vyberte si výhodné sady parfémů a ušetřete na nákupu originálních vůní."
          canonical={`${SITE_URL}/vyhodne-sady`}
        />
        <div className="w-full bg-luxury-dark min-h-screen flex items-center justify-center pt-40">
          <div className="text-center">
            <p className="text-red-500 text-lg mb-6">{error}</p>
            <button
              onClick={() => router.push('/')}
              className="px-8 py-3 bg-luxury-gold text-luxury-dark font-bold rounded hover:bg-yellow-300 transition-all"
            >
              Zpět na hlavní stránku
            </button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <Seo
        title="Výhodné sady parfémů | Vystříkejto.cz"
        description="Objevte výhodné sady originálních parfémů a ušetřete na nákupu."
        canonical={`${SITE_URL}/vyhodne-sady`}
        jsonLd={breadcrumbsJsonLd([
          { name: 'Domů', href: '/' },
          { name: 'Výhodné sady' },
        ])}
      />
      <section className="w-full bg-luxury-dark px-4 pb-20 pt-28 sm:px-6 lg:px-[5vw] lg:pb-24 lg:pt-36" data-section="bundles-products">
        <div className="mx-auto max-w-[1600px]">
          <Breadcrumbs items={[{ name: 'Domů', href: '/' }, { name: 'Výhodné sady' }]} />
          <header className="mb-10 flex items-end justify-between gap-6">
            <div>
              <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-luxury-gold">
                Výhodné sady
              </p>
              <h1 className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl lg:text-6xl">
                Ušetřete s našimi sadami
              </h1>
            </div>
            <span className="hidden shrink-0 text-xs text-luxury-light/45 sm:block">
              {formatBundleCount(bundles.length)}
            </span>
          </header>

          {bundles.length > 0 ? (
            <>
              <div className="mb-7 flex items-center justify-between gap-3 border-t border-luxury-light/15 pt-5 text-xs text-luxury-light/45">
                <span>{formatBundleCount(bundles.length)}</span>
                <span className="hidden sm:inline">Provedení zvolíte u každé sady</span>
              </div>

              <div className="mb-20 grid grid-cols-1 gap-x-4 gap-y-12 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-[18px]">
                {bundles.map((bundle) => {
                  const variant = getSelectedVariant(bundle);
                  const variantOriginalPrice = Number(variant.originalPrice || bundle.originalPrice);
                  const variantCurrentPrice = Number(variant.currentPrice || bundle.currentPrice);
                  const hasDiscount = variantOriginalPrice > 0 && variantCurrentPrice < variantOriginalPrice;
                  const discountPercentage = hasDiscount
                    ? Math.round(((variantOriginalPrice - variantCurrentPrice) / variantOriginalPrice) * 100)
                    : 0;
                  const displayedProducts = getVariantProductsForDisplay(bundle);
                  const bundleAvailable = isBundleAvailable(bundle);

                  return (
                    <article key={bundle.id} className={`group min-w-0 ${bundleAvailable ? '' : 'opacity-60'}`}>
                      <div className={`relative aspect-square overflow-hidden bg-[#0d0d0d] ${bundleAvailable ? '' : 'grayscale'}`}>
                        <Link
                          href={`/vyhodne-sady/${bundle.slug}`}
                          aria-label={`Zobrazit sadu ${bundle.name}`}
                          className="grid h-full grid-cols-3 grid-rows-2"
                        >
                          {displayedProducts.slice(0, 6).map((product, idx) => (
                            <div key={`${product.id}-${idx}`} className="relative flex items-center justify-center overflow-hidden bg-black/30">
                              <img
                                src={product.image}
                                alt={product.name}
                                className={`h-full w-full object-cover transition-transform duration-700 ease-out ${
                                  bundleAvailable ? 'group-hover:scale-[1.025]' : ''
                                } ${product.productStock < product.volumeMl ? 'opacity-50' : ''}`}
                                onError={(event) => {
                                  (event.target as HTMLImageElement).src = '/images/logo.png';
                                }}
                              />
                              {product.productStock < product.volumeMl && (
                                <div className="absolute inset-0 flex items-center justify-center bg-black/60">
                                  <span className="px-1 text-center text-[10px] font-bold uppercase text-red-300">Vyprodáno</span>
                                </div>
                              )}
                            </div>
                          ))}
                        </Link>
                        <Link
                          href={`/vyhodne-sady/${bundle.slug}`}
                          className="absolute bottom-3 left-3 right-3 z-20 hidden min-h-12 translate-y-16 items-center justify-between bg-white/95 px-4 text-left text-xs font-bold text-[#151515] transition-all duration-300 hover:bg-luxury-gold group-hover:translate-y-0 md:flex"
                        >
                          <span>Zobrazit sadu</span>
                          <svg className="h-4 w-4" 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>
                        </Link>
                      </div>

                      <div className="px-px pt-4">
                        <h2 className="mb-1.5 min-h-[2.5em] text-sm font-semibold leading-[1.25] text-luxury-light sm:text-[15px]">
                          <Link href={`/vyhodne-sady/${bundle.slug}`} className="text-left hover:text-luxury-gold">
                            {bundle.name}
                          </Link>
                        </h2>
                        <p className="mb-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-luxury-light/45">
                          {displayedProducts.length} vůní v sadě
                        </p>
                        <Link
                          href={`/vyhodne-sady/${bundle.slug}`}
                          className="mb-3 text-left text-[11px] font-semibold text-luxury-gold hover:text-yellow-300 md:hidden"
                        >
                          Zobrazit sadu
                        </Link>

                        {bundle.variants && bundle.variants.length > 0 && (
                          <div className="mt-3 flex flex-wrap gap-1.5">
                            {bundle.variants.map((bundleVariant) => {
                              const isSelected = (selectedVariants[bundle.id] || bundle.variants![0].id) === bundleVariant.id;
                              const variantAvailable = isBundleVariantAvailable(bundleVariant);

                              return (
                                <button
                                  key={bundleVariant.id}
                                  type="button"
                                  disabled={!variantAvailable}
                                  aria-label={`${bundleVariant.name}${variantAvailable ? '' : ', vyprodáno'}`}
                                  title={variantAvailable ? undefined : 'Vyprodáno'}
                                  onClick={() => {
                                    setSelectedVariants((current) => ({
                                      ...current,
                                      [bundle.id]: bundleVariant.id,
                                    }));
                                  }}
                                  className={`h-9 min-w-[54px] flex-1 border px-2 text-[11px] font-semibold transition-colors ${
                                    !variantAvailable
                                      ? 'cursor-not-allowed border-red-500/45 bg-red-500/10 text-red-400/80'
                                      : isSelected
                                      ? 'border-luxury-gold bg-luxury-gold text-luxury-dark'
                                      : 'border-luxury-light/20 bg-transparent text-luxury-light hover:border-luxury-gold/70'
                                  }`}
                                >
                                  {bundleVariant.name}
                                </button>
                              );
                            })}
                          </div>
                        )}

                        <div className="mt-4 flex items-end justify-between gap-3 border-t border-luxury-light/10 pt-3">
                          {hasDiscount && (
                            <div>
                              <p className="text-[10px] uppercase tracking-[0.1em] text-luxury-light/40">Běžně</p>
                              <p className="text-lg font-semibold text-luxury-light/55">
                                {formatPrice(variantOriginalPrice)}
                              </p>
                            </div>
                          )}
                          {hasDiscount && (
                            <p className="mb-0.5 whitespace-nowrap bg-luxury-gold px-2 py-1 text-center text-[9px] font-bold uppercase leading-tight tracking-[0.08em] text-luxury-dark sm:text-[10px]">
                              Ušetříte {discountPercentage} %
                            </p>
                          )}
                          <div className="text-right">
                            <p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-luxury-light/45">Cena sady</p>
                            <p className="mt-0.5 whitespace-nowrap text-lg font-bold text-luxury-gold">
                              {formatPrice(variantCurrentPrice)}
                            </p>
                          </div>
                        </div>

                        <button
                          type="button"
                          onClick={() => handleAddBundleToCart(bundle)}
                          disabled={!bundleAvailable || addedToCart[bundle.id]}
                          className={`mt-3 h-11 w-full border px-3 text-sm font-bold transition-colors ${
                            addedToCart[bundle.id]
                              ? 'border-green-500 bg-green-500/20 text-green-400'
                              : !bundleAvailable
                                ? 'cursor-not-allowed border-luxury-light/15 bg-luxury-light/10 text-luxury-light/35'
                                : 'border-luxury-gold bg-luxury-gold text-luxury-dark hover:border-yellow-300 hover:bg-yellow-300'
                          }`}
                          title={!bundleAvailable ? 'Sada obsahuje vyprodané produkty' : ''}
                        >
                          {addedToCart[bundle.id] ? '✓ Přidáno' : !bundleAvailable ? 'Vyprodáno' : 'Přidat do košíku'}
                        </button>
                      </div>
                    </article>
                  );
                })}
              </div>
            </>
          ) : (
            <div className="text-center py-24">
              <h2 className="text-2xl font-aptos font-bold text-luxury-light mb-4">Žádné sady nejsou k dispozici</h2>
              <p className="text-luxury-light/70 mb-8">V tuto chvíli nemáme připravené žádné výhodné balíčky</p>
              <button
                onClick={() => router.push('/')}
                className="px-8 py-3 bg-luxury-gold text-luxury-dark font-bold rounded hover:bg-yellow-300 transition-all"
              >
                Zpět na hlavní stránku
              </button>
            </div>
          )}
        </div>
      </section>

    </>
  );
};

export const getServerSideProps: GetServerSideProps<BundlesPageProps> = async ({ req }) => {
  if (!BUNDLES_ENABLED) return { notFound: true };

  const bundles = await fetchFromApi<Bundle[]>(req, '/api/bundles');
  return {
    props: {
      initialBundles: bundles || [],
    },
  };
};

export default BundlesPage;
