import { BUNDLES_ENABLED } from '@/lib/features';
import type { GetServerSideProps, NextPage } from 'next';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import Breadcrumbs, { breadcrumbsJsonLd } from '../../components/Breadcrumbs';
import ProductImage from '../../components/ProductImage';
import Seo from '../../components/Seo';
import { useCart } from '../../context/CartContext';
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[];
}

interface BundleDetailProps {
  bundle: Bundle;
}

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

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

const BundleDetail: NextPage<BundleDetailProps> = ({ bundle }) => {
  const { addItem } = useCart();
  const variants = bundle.variants || [];
  const initialVariant = variants.find(isVariantAvailable) || variants[0];
  const [selectedVariantId, setSelectedVariantId] = useState(initialVariant?.id || null);
  const [quantity, setQuantity] = useState(1);
  const [addedToCart, setAddedToCart] = useState(false);

  useEffect(() => {
    const nextInitialVariant = variants.find(isVariantAvailable) || variants[0];
    setSelectedVariantId(nextInitialVariant?.id || null);
    setQuantity(1);
    setAddedToCart(false);
  }, [bundle.id]);

  const selectedVariant = useMemo(
    () => variants.find((variant) => variant.id === selectedVariantId) || initialVariant,
    [initialVariant, selectedVariantId, variants],
  );
  const selectedProducts = selectedVariant?.products || bundle.products;
  const available = selectedVariant ? isVariantAvailable(selectedVariant) : false;
  const originalPrice = Number(selectedVariant?.originalPrice || bundle.originalPrice);
  const currentPrice = Number(selectedVariant?.currentPrice || bundle.currentPrice);
  const hasDiscount = originalPrice > 0 && currentPrice < originalPrice;
  const discountPercentage = hasDiscount
    ? Math.round(((originalPrice - currentPrice) / originalPrice) * 100)
    : 0;
  const displayImage = selectedProducts[0]?.image || bundle.image;

  const selectVariant = (variantId: number) => {
    setSelectedVariantId(variantId);
    setQuantity(1);
    setAddedToCart(false);
  };

  const handleAddToCart = async () => {
    if (!selectedVariant || !available || !bundle.bundleProductId) return;

    for (let index = 0; index < quantity; index += 1) {
      await addItem({
        variantId: selectedVariant.id,
        productId: bundle.bundleProductId,
        productName: bundle.name,
        productSlug: bundle.slug,
        brandName: 'Výhodná sada',
        volume: selectedVariant.name,
        price: currentPrice,
        image: displayImage,
        productType: 'bundle',
      });
    }

    setAddedToCart(true);
    window.setTimeout(() => setAddedToCart(false), 2000);
  };

  const description = `Výhodná sada ${bundle.name} obsahuje ${selectedProducts.length} pečlivě vybraných vůní. Zvolte provedení sady a ušetřete oproti nákupu samostatně.`;
  const canonical = `${SITE_URL}/vyhodne-sady/${bundle.slug}`;

  return (
    <>
      <Seo
        title={`${bundle.name} – výhodná sada parfémů | Vystříkejto.cz`}
        description={description}
        canonical={canonical}
        ogImage={displayImage}
        ogType="product"
        jsonLd={[
          breadcrumbsJsonLd([
            { name: 'Domů', href: '/' },
            { name: 'Výhodné sady', href: '/vyhodne-sady' },
            { name: bundle.name },
          ]),
          {
            '@context': 'https://schema.org',
            '@type': 'Product',
            name: bundle.name,
            description,
            image: selectedProducts.map((product) => product.image),
            url: canonical,
            offers: variants.map((variant) => ({
              '@type': 'Offer',
              priceCurrency: 'CZK',
              price: Number(variant.currentPrice).toFixed(2),
              availability: isVariantAvailable(variant)
                ? 'https://schema.org/InStock'
                : 'https://schema.org/OutOfStock',
              url: canonical,
              name: variant.name,
            })),
          },
        ]}
      />

      <div className="min-h-screen w-full bg-luxury-dark pb-12 pt-20 md:pb-16 md:pt-24">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="md:hidden">
            <Breadcrumbs
              items={[
                { name: 'Domů', href: '/' },
                { name: 'Výhodné sady', href: '/vyhodne-sady' },
                { name: bundle.name },
              ]}
            />
          </div>

          <div className="flex flex-col gap-6 md:grid md:grid-cols-[0.88fr_1.12fr] lg:gap-8">
            <div className="order-2 flex flex-col items-center justify-start gap-3 md:order-1">
              <div className="w-full max-w-lg">
                <div className="grid aspect-square w-full grid-cols-3 grid-rows-2 overflow-hidden bg-[#0d0d0d]">
                  {selectedProducts.slice(0, 6).map((product, index) => (
                    <Link
                      key={`${product.id}-${index}`}
                      href={`/product/${product.slug}`}
                      aria-label={`Zobrazit ${product.name}`}
                      className="group/image relative overflow-hidden bg-black/30"
                    >
                      <ProductImage
                        src={product.image}
                        alt={product.name}
                        priority={index < 3}
                        className="h-full w-full object-cover transition-transform duration-700 ease-out group-hover/image:scale-[1.035]"
                      />
                      {!product.productStock || product.productStock < product.volumeMl ? (
                        <span className="absolute inset-0 grid place-items-center bg-black/60 px-2 text-center text-[10px] font-bold uppercase text-red-300">
                          Vyprodáno
                        </span>
                      ) : null}
                    </Link>
                  ))}
                </div>

                <div className="mt-4 w-full md:hidden">
                  <p className="mb-2 text-base font-semibold uppercase tracking-widest text-luxury-gold sm:text-lg">
                    Výhodná sada
                  </p>
                  <h1 className="text-3xl font-black text-luxury-light sm:text-4xl">{bundle.name}</h1>
                  <div className="mt-2 h-1 w-16 bg-luxury-gold" />
                </div>
              </div>
            </div>

            <div className="order-3 flex flex-col gap-4 md:order-2 md:gap-2">
              <div className="hidden md:block">
                <p className="text-sm font-semibold uppercase tracking-widest text-luxury-gold lg:text-base">
                  Výhodná sada
                </p>
                <h1 className="mb-1 mt-2 text-3xl font-black text-luxury-light lg:text-4xl">{bundle.name}</h1>
                <div className="h-0.5 w-12 bg-luxury-gold" />
                <p className={`mt-3 whitespace-nowrap text-2xl font-black lg:text-3xl ${available ? 'text-luxury-gold' : 'text-red-400'}`}>
                  {formatPrice(currentPrice)} Kč
                </p>
              </div>

              <div className="order-3 border-t border-luxury-gold/20 pt-3 md:order-none">
                <p className="text-sm leading-[1.5] text-luxury-light/75">{description}</p>
                <div className="mt-3 flex items-center gap-3">
                  {hasDiscount ? (
                    <>
                      <span className="text-sm text-luxury-light/55">Běžně {formatPrice(originalPrice)} Kč</span>
                      <span className="bg-luxury-gold px-2 py-1 text-[10px] font-bold uppercase tracking-[0.08em] text-luxury-dark">
                        Ušetříte {discountPercentage} %
                      </span>
                    </>
                  ) : null}
                </div>
              </div>

              <div className="order-1 grid gap-2 border-t border-luxury-gold/20 pt-3 md:order-none">
                <div className="grid gap-[clamp(4px,1.2vw,8px)] border-b border-luxury-gold/15 py-[clamp(5px,1.2vw,8px)]">
                  <div className="flex items-center justify-between gap-3 px-0.5">
                    <div className="flex min-w-0 items-baseline gap-[clamp(6px,1.2vw,10px)]">
                      <p className="shrink-0 text-[clamp(12px,1.2vw,15px)] font-bold uppercase tracking-[0.14em] text-luxury-gold">
                        Provedení sady
                      </p>
                      <p className="truncate text-[clamp(9px,0.9vw,11px)] leading-tight text-luxury-light/50">
                        Každá vůně v sadě
                      </p>
                    </div>
                    <span className="shrink-0 text-[9px] font-semibold uppercase tracking-wider text-luxury-light/40">
                      {variants.length} varianty
                    </span>
                  </div>

                  <div className="flex items-center gap-[clamp(8px,1.5vw,18px)] overflow-x-auto pb-0.5 pt-2">
                    {variants.map((variant) => {
                      const variantAvailable = isVariantAvailable(variant);
                      const selected = selectedVariant?.id === variant.id;

                      return (
                        <button
                          type="button"
                          key={variant.id}
                          disabled={!variantAvailable}
                          aria-pressed={selected}
                          onClick={() => selectVariant(variant.id)}
                          className={`relative flex min-h-[54px] min-w-max flex-1 flex-col items-center justify-center gap-0.5 whitespace-nowrap rounded-md border px-[clamp(7px,1vw,12px)] py-2 text-center transition-all duration-200 ${
                            !variantAvailable
                              ? 'cursor-not-allowed border-red-500/30 bg-red-500/5 text-red-300/45'
                              : selected
                                ? 'border-luxury-gold bg-luxury-gold text-luxury-dark shadow-md shadow-luxury-gold/15'
                                : 'border-luxury-gold/35 bg-transparent text-luxury-light hover:border-luxury-gold/75 hover:bg-luxury-gold/5'
                          }`}
                        >
                          <span className={`text-[clamp(11px,calc(0.95vw+1px),13px)] font-semibold ${selected ? 'text-luxury-dark/65' : 'text-luxury-light/55'}`}>
                            {variant.name}
                          </span>
                          <b className={`text-[clamp(14px,1.35vw,18px)] ${selected ? 'text-luxury-dark' : !variantAvailable ? 'text-red-300/55' : 'text-luxury-light'}`}>
                            {variantAvailable ? `${formatPrice(variant.currentPrice)} Kč` : 'Vyprodáno'}
                          </b>
                        </button>
                      );
                    })}
                  </div>
                </div>
              </div>

              {available ? (
                <div className="order-2 flex flex-col gap-2 md:order-none">
                  <div className="flex items-stretch gap-2">
                    <div className="flex min-h-[52px] items-center rounded-lg border border-luxury-gold/40">
                      <button
                        type="button"
                        onClick={() => setQuantity(Math.max(1, quantity - 1))}
                        className="h-full px-3 text-luxury-gold transition-colors hover:bg-luxury-gold/10"
                        aria-label="Snížit počet kusů"
                      >
                        −
                      </button>
                      <span className="flex min-w-12 flex-col items-center px-3 text-center font-bold text-luxury-light">
                        <small className="text-[8px] font-semibold uppercase tracking-wider text-luxury-light/45">Počet</small>
                        {quantity}
                      </span>
                      <button
                        type="button"
                        onClick={() => setQuantity(quantity + 1)}
                        className="h-full px-3 text-luxury-gold transition-colors hover:bg-luxury-gold/10"
                        aria-label="Zvýšit počet kusů"
                      >
                        +
                      </button>
                    </div>

                    <button
                      type="button"
                      onClick={handleAddToCart}
                      className={`min-h-[52px] flex-1 rounded-lg px-4 py-3 text-base font-bold transition-all duration-300 ${
                        addedToCart
                          ? 'bg-green-500 text-white'
                          : 'bg-luxury-gold text-luxury-dark shadow-lg shadow-luxury-gold/20 hover:bg-yellow-300'
                      }`}
                    >
                      {addedToCart ? '✓ Přidáno do košíku' : 'Přidat do košíku'}
                    </button>
                  </div>
                  <p className="text-xs text-luxury-light/55">Skladem · standardní doručení do 2 pracovních dnů.</p>
                </div>
              ) : (
                <div className="order-2 border-t border-luxury-gold/20 pt-6 md:order-none">
                  <div className="w-full rounded-lg border border-red-500/40 bg-red-500/20 px-6 py-4 text-center">
                    <p className="font-bold text-red-400">VYPRODÁNO</p>
                  </div>
                </div>
              )}
            </div>
          </div>

          <section className="mt-5 border-t border-luxury-gold/40 pt-6 sm:mt-6">
            <header className="mb-8 sm:mb-10">
              <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-luxury-gold">{selectedProducts.length} vůní</p>
              <h2 className="text-3xl font-black text-luxury-light sm:text-4xl">Obsah sady</h2>
              <div className="mt-2 h-1 w-16 bg-luxury-gold" />
            </header>

            <div className="grid grid-cols-2 gap-x-3 gap-y-8 sm:grid-cols-3 sm:gap-x-4 lg:grid-cols-6">
              {selectedProducts.map((product) => {
                const productAvailable = product.productStock >= product.volumeMl;

                return (
                  <article key={product.variantId} className={`group min-w-0 ${productAvailable ? '' : 'opacity-60'}`}>
                    <Link href={`/product/${product.slug}`} className="block aspect-[2/3] overflow-hidden bg-[#0d0d0d]">
                      <ProductImage
                        src={product.image}
                        alt={product.name}
                        className="h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.025]"
                      />
                    </Link>
                    <div className="pt-3">
                      <p className="text-[9px] font-semibold uppercase tracking-[0.12em] text-luxury-light/45">{product.brandName}</p>
                      <h3 className="my-1 min-h-[2.5em] text-sm font-semibold leading-[1.25] text-luxury-light">
                        <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="text-xs font-semibold text-luxury-gold">{product.volume}</p>
                        <p className="text-xs font-bold text-luxury-gold">{formatPrice(product.price)} Kč</p>
                      </div>
                      {!productAvailable ? <p className="mt-1 text-[10px] font-semibold uppercase text-red-400">Vyprodáno</p> : null}
                    </div>
                  </article>
                );
              })}
            </div>
          </section>
        </div>
      </div>
    </>
  );
};

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

  const slug = params?.slug;
  if (!slug || Array.isArray(slug)) return { notFound: true };

  const bundles = await fetchFromApi<Bundle[]>(req, '/api/bundles');
  const bundle = bundles?.find((item) => item.slug === slug);
  if (!bundle) return { notFound: true };

  return { props: { bundle } };
};

export default BundleDetail;
