import { useState } from 'react';
import type { ShopOffer } from '../data/mock';

interface Props {
  offers: ShopOffer[];
  lowestPrice: number;
  selectedSize?: string | null;
  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, sneakerData }: Props) {
  const filtered = selectedSize
    ? offers.filter((o) => o.sizes.includes(selectedSize))
    : offers;
  const sorted = [...filtered].sort((a, b) => a.price - b.price);

  const handleOutboundClick = (offer: ShopOffer) => {
    if (!sneakerData) return;
    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,
    });
  };

  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"
                  onClick={() => handleOutboundClick(offer)}
                  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>
  );
}
