import { useState, useEffect } from 'react';

interface WatchlistItem {
  id: number;
  product_id: number;
  target_price: number | null;
  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 WatchlistPageApp() {
  const [items, setItems] = useState<WatchlistItem[]>([]);
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [editingPrice, setEditingPrice] = useState<number | null>(null);
  const [priceInput, setPriceInput] = useState('');

  useEffect(() => {
    Promise.all([
      fetch('/api/auth/session').then(r => r.json()),
      fetch('/api/watchlist').then(r => r.json()).catch(() => ({ items: [] })),
    ]).then(([session, watchlist]) => {
      setUser(session.user);
      setItems(watchlist.items || []);
      setLoading(false);
    });
  }, []);

  const removeItem = async (productId: number) => {
    await fetch('/api/watchlist', {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId }),
    });
    setItems(items.filter(i => i.product_id !== productId));
  };

  const updateTargetPrice = async (productId: number) => {
    const price = priceInput ? parseFloat(priceInput) : null;
    await fetch('/api/watchlist', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, target_price: price }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, target_price: price } : i));
    setEditingPrice(null);
    setPriceInput('');
  };

  if (loading) {
    return <div className="text-center text-white/40 py-12">Laden...</div>;
  }

  if (!user) {
    return (
      <div className="text-center py-12">
        <p className="text-white/60 mb-4">Log in om je watchlist te bekijken</p>
        <a href="/" className="inline-block rounded-lg bg-[#00FF6A] px-6 py-2.5 font-bold text-black">
          Naar home
        </a>
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-4xl mb-4">👟</p>
        <p className="text-white/60 mb-4">Je watchlist is nog leeg</p>
        <a href="/" className="inline-block rounded-lg bg-[#00FF6A] px-6 py-2.5 font-bold text-black">
          Ontdek sneakers
        </a>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <p className="text-sm text-white/40">{items.length} sneaker{items.length !== 1 ? 's' : ''} op je watchlist</p>
      {items.map(item => {
        const img = item.cutout_image_url || item.image_url;
        const hasDiscount = item.original_price && item.lowest_price && item.lowest_price < item.original_price;
        
        return (
          <div key={item.id} className="flex gap-4 rounded-xl border border-white/10 bg-white/5 p-4">
            <a href={`/sneakers/${item.slug}`} className="shrink-0">
              <img src={img} alt={item.name} className="h-24 w-24 rounded-lg object-contain bg-white/5" />
            </a>
            <div className="flex-1 min-w-0">
              <p className="text-[11px] font-bold uppercase tracking-widest text-white/40">{item.brand}</p>
              <a href={`/sneakers/${item.slug}`} className="font-semibold text-white hover:text-[#00FF6A] transition-colors">
                {item.name}
              </a>
              {item.colorway && <p className="text-xs text-white/40">{item.colorway}</p>}
              
              <div className="mt-2 flex flex-wrap items-center gap-3">
                {item.lowest_price ? (
                  <span className="text-lg font-black text-[#00FF6A]">
                    €{Number(item.lowest_price).toFixed(2).replace('.', ',')}
                  </span>
                ) : (
                  <span className="text-sm text-white/40">Niet beschikbaar</span>
                )}
                {hasDiscount && (
                  <span className="text-sm text-white/40 line-through">
                    €{Number(item.original_price).toFixed(2).replace('.', ',')}
                  </span>
                )}
                <span className="text-xs text-white/30">{item.shop_count} shop{Number(item.shop_count) !== 1 ? 's' : ''}</span>
              </div>

              {/* Target price */}
              <div className="mt-2 flex items-center gap-2">
                {editingPrice === item.product_id ? (
                  <>
                    <span className="text-xs text-white/40">Alert onder €</span>
                    <input
                      type="number"
                      value={priceInput}
                      onChange={e => setPriceInput(e.target.value)}
                      step="0.01"
                      min="0"
                      className="w-20 rounded border border-white/10 bg-white/5 px-2 py-1 text-sm text-white focus:border-[#00FF6A]/50 focus:outline-none"
                      autoFocus
                    />
                    <button onClick={() => updateTargetPrice(item.product_id)} className="text-xs text-[#00FF6A] hover:underline">Opslaan</button>
                    <button onClick={() => setEditingPrice(null)} className="text-xs text-white/30 hover:text-white/60">×</button>
                  </>
                ) : (
                  <button
                    onClick={() => { setEditingPrice(item.product_id); setPriceInput(item.target_price?.toString() || ''); }}
                    className="text-xs text-white/40 hover:text-[#00FF6A] transition-colors"
                  >
                    {item.target_price
                      ? `🎯 Alert onder €${Number(item.target_price).toFixed(2).replace('.', ',')} — wijzig`
                      : '+ Prijsalert instellen'}
                  </button>
                )}
              </div>
            </div>
            
            <button
              onClick={() => removeItem(item.product_id)}
              className="shrink-0 self-start rounded-full p-2 text-white/30 hover:bg-red-500/10 hover:text-red-400 transition-colors"
              title="Verwijderen"
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="w-4 h-4">
                <path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
              </svg>
            </button>
          </div>
        );
      })}
    </div>
  );
}
