import { useState } from 'react';
import type { ShopOffer } from '../data/mock';
import { trackClick, getPageSource } from '../lib/tracking';

interface Props {
  offers: ShopOffer[];
  lowestPrice: number;
  selectedSize?: string | null;
  productId?: string;
  sneakerData?: {
    item_id: string;
    item_name: string;
    item_brand: string;
    price: number;
  };
}

function SizeChips({ sizes }: { sizes: string[] }) {
  const [open, setOpen] = useState(false);
  const sorted = [...sizes].sort((a, b) => parseFloat(a) - parseFloat(b));
  const maxShow = 10;
  const hasMore = sorted.length > maxShow;
  const visible = open ? sorted : sorted.slice(0, maxShow);

  return (
    <div>
      <button
        onClick={(e) => { e.preventDefault(); setOpen(!open); }}
        className="text-xs text-text-muted hover:text-accent transition-colors"
      >
        · {sizes.length} maten {open ? '▾' : '▸'}
      </button>
      {open && (
        <div className="mt-1 flex flex-wrap gap-1">
          {visible.map((size) => (
            <span key={size} className="rounded bg-bg-elevated px-1.5 py-0.5 text-[10px] text-text-muted">
              {size}
            </span>
          ))}
          {hasMore && !open && (
            <span className="text-[10px] text-text-muted">en {sorted.length - maxShow} meer</span>
          )}
        </div>
      )}
    </div>
  );
}

export default function PriceComparisonTable({ offers, lowestPrice, selectedSize, productId, sneakerData }: Props) {
  const filtered = selectedSize
    ? offers.filter((o) => o.sizes.includes(selectedSize))
    : offers;

  // When a size is selected, use the size-specific price and URL from sizeDetails
  const withEffectivePricing = filtered.map((o) => {
    if (!selectedSize) return o;
    const detail = o.sizeDetails?.find((d) => d.size === selectedSize);
    if (!detail) return o;
    return {
      ...o,
      price: detail.price,
      url: detail.url ?? o.url,
    };
  });

  const sorted = [...withEffectivePricing].sort((a, b) => a.price - b.price);

  const handleOutboundClick = async (e: React.MouseEvent<HTMLAnchorElement>, offer: ShopOffer, position: number) => {
    e.preventDefault();

    // GA4 dataLayer events
    if (sneakerData) {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ ecommerce: null });
      window.dataLayer.push({
        event: 'select_promotion',
        ecommerce: {
          promotion_id: offer.shop,
          promotion_name: offer.shop,
          items: [sneakerData],
        },
      });
      window.dataLayer.push({
        event: 'outbound_click',
        destination_url: offer.url,
        shop_name: offer.shop,
      });
    }

    // Track click server-side and get redirect URL with clickRef
    const result = await trackClick({
      product_id: productId || sneakerData?.item_id || '0',
      shop_id: offer.shop,
      url: offer.url,
      source: getPageSource(),
      source_detail: offer.shop,
      position,
    });

    // Klaviyo affiliate_click event (clickRef comes from redirect URL)
    const redirectUrl = result?.redirect_url || offer.url;
    let clickRef = '';
    try { clickRef = new URL(redirectUrl).searchParams.get('clickRef') || ''; } catch (_) {}
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'affiliate_click',
      product_id: sneakerData?.item_id || productId || '',
      product_name: sneakerData?.item_name || '',
      brand: sneakerData?.item_brand || '',
      shop: offer.shop,
      price: offer.price,
      click_ref: clickRef,
      affiliate_url: redirectUrl,
    });

    // Redirect to affiliate URL (with clickRef appended)
    window.open(redirectUrl, '_blank', 'noopener,noreferrer');
  };

  return (
    <div className="overflow-hidden rounded-2xl border border-border/50">
      <div className="bg-bg-elevated px-4 py-3">
        <h3 className="text-sm font-bold uppercase tracking-widest text-text-muted">
          Prijsvergelijking
          {selectedSize && <span className="ml-2 text-accent">· Maat {selectedSize}</span>}
        </h3>
      </div>
      {sorted.length === 0 ? (
        <div className="px-4 py-8 text-center text-sm text-text-muted">
          Geen shops gevonden met maat {selectedSize}
        </div>
      ) : (
        <div className="divide-y divide-border/30">
          {sorted.map((offer, i) => {
            const isLowest = offer.price === Math.min(...sorted.map(o => o.price));
            return (
              <div
                key={offer.shop}
                className={`flex items-center gap-4 px-4 py-4 transition-colors hover:bg-bg-hover ${
                  i === 0 ? 'bg-accent/5' : ''
                }`}
              >
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-text">{offer.shop}</span>
                    {isLowest && (
                      <span className="rounded-full bg-accent/20 px-2 py-0.5 text-[10px] font-bold text-accent">
                        LAAGSTE
                      </span>
                    )}
                  </div>
                  <div className="mt-1 flex items-center gap-2">
                    {offer.inStock ? (
                      <span className="text-xs text-accent">✓ Op voorraad</span>
                    ) : (
                      <span className="text-xs text-danger">✗ Uitverkocht</span>
                    )}
                    {offer.sizes.length > 0 && <SizeChips sizes={offer.sizes} />}
                  </div>
                </div>

                <div className="text-right">
                  <div className="flex items-baseline gap-2">
                    {offer.originalPrice && offer.originalPrice > offer.price && (
                      <span className="text-sm text-text-muted line-through">
                        €{offer.originalPrice.toFixed(2).replace('.', ',')}
                      </span>
                    )}
                    <span className={`text-lg font-black ${isLowest ? 'text-accent' : 'text-text'}`}>
                      €{offer.price.toFixed(2).replace('.', ',')}
                    </span>
                  </div>
                </div>

                <a
                  href={offer.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  data-shop={offer.shop}
                  data-price={offer.price}
                  onClick={(e) => handleOutboundClick(e, offer, i)}
                  className={`rounded-xl px-4 py-2 text-sm font-bold transition-all ${
                    offer.inStock
                      ? 'bg-accent text-bg hover:bg-accent-dim hover:shadow-lg hover:shadow-accent/20'
                      : 'cursor-not-allowed bg-surface text-text-muted'
                  }`}
                >
                  Bekijk
                </a>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
