import { useState, useEffect } from 'react';

interface RecommendedItem {
  id: number;
  name: string;
  brand: string;
  slug: string;
  image_url: string;
  cutout_image_url: string | null;
  colorway: string;
  lowest_price: number | null;
  shop_count: number;
  original_price: number | null;
}

export default function ForYouSection() {
  const [items, setItems] = useState<RecommendedItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/user/recommendations')
      .then(r => r.json())
      .then(data => {
        setItems(data.items || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  if (loading) return null;
  if (items.length === 0) return null;

  return (
    <div className="mt-10">
      <h2 className="mb-4 text-lg font-bold text-text">Voor jou</h2>
      <p className="mb-4 text-sm text-text-muted">Gebaseerd op je watchlist en voorkeuren</p>
      <div className="flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 snap-x">
        {items.map(item => {
          const lowestPrice = item.lowest_price ? parseFloat(String(item.lowest_price)) : null;
          const originalPrice = item.original_price ? parseFloat(String(item.original_price)) : null;
          const hasDiscount = originalPrice && lowestPrice && lowestPrice < originalPrice;
          const discountPct = hasDiscount ? Math.round((1 - lowestPrice / originalPrice) * 100) : 0;

          return (
            <a
              key={item.id}
              href={`/sneakers/${item.slug}`}
              className="flex-none w-44 snap-start rounded-xl border border-border/30 bg-bg-card p-3 transition-all hover:border-accent/30"
            >
              <img
                src={`/api/img/${item.id}`}
                alt={item.name}
                width={176}
                height={112}
                className="mb-2 h-28 w-full rounded-lg object-contain bg-white"
                loading="lazy"
                decoding="async"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = '/img/sneaker-placeholder.svg';
                }}
              />
              <p className="text-[10px] font-bold uppercase tracking-widest text-text-muted">{item.brand}</p>
              <p className="text-sm font-semibold text-text line-clamp-1">{item.name}</p>
              <div className="mt-1 flex items-center gap-2">
                {lowestPrice ? (
                  <span className="text-sm font-black text-accent">
                    &euro;{lowestPrice.toFixed(2).replace('.', ',')}
                  </span>
                ) : (
                  <span className="text-xs text-text-muted">N/A</span>
                )}
                {discountPct > 0 && (
                  <span className="rounded bg-accent/15 px-1.5 py-0.5 text-[10px] font-bold text-accent">
                    -{discountPct}%
                  </span>
                )}
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}
