'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';
import { DealSelectButton } from './DealPanel';

const CATEGORIES = [
  { id: 'all', label: 'Tout' },
  { id: 'item_', label: 'Items' },
  { id: 'item_weapon', label: 'Armes' },
  { id: 'item_vehicle', label: 'Vehicules' },
  { id: 'currency_', label: 'Monnaies' },
  { id: 'character_', label: 'Personnages' },
  { id: 'empire_', label: 'Empire' },
];

const MARKET_TYPES = [
  { id: 'white', label: 'Marché Blanc' },
  { id: 'all', label: 'Tout' },
  { id: 'black', label: 'Marché Noir' },
];

// Inline SVG search icon
function IconSearch({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>
    </svg>
  );
}

interface ListingData {
  id: string;
  title: string;
  category: string;
  market_type: string;
  suggested_value: number;
  status: string;
  view_count: number;
  seller: { id: string; username: string } | null;
  created_at: string;
}

export function MarketBrowser() {
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [selectedMarket, setSelectedMarket] = useState('all');
  const [listings, setListings] = useState<ListingData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadListings();
  }, [selectedMarket, selectedCategory]);

  async function loadListings() {
    setLoading(true);
    setError(null);
    try {
      const filters: Record<string, string | undefined> = {};
      if (selectedMarket !== 'all') filters.market = selectedMarket;
      if (selectedCategory !== 'all') filters.category = selectedCategory;
      const data = await api.marketplace.getListings(filters) as ListingData[];
      setListings(data);
    } catch (err: any) {
      setError(err.message || 'Erreur de chargement');
      setListings([]);
    } finally {
      setLoading(false);
    }
  }

  const filtered = listings.filter(l => {
    if (search && !l.title.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div>
      {/* Filters */}
      <div className="flex gap-3 mb-4 flex-wrap">
        <div className="flex-1 min-w-[200px] relative">
          <div className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'var(--text-muted)' }}>
            <IconSearch />
          </div>
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Rechercher..."
            className="w-full pl-8 pr-4 py-2 rounded-lg text-sm outline-none"
            style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
          />
        </div>
        <div className="flex gap-1">
          {CATEGORIES.map(c => {
            const isActive = selectedCategory === c.id;
            const isTout = c.id === 'all';
            return (
              <button key={c.id} onClick={() => setSelectedCategory(c.id)}
                className="px-3 py-2 rounded-lg text-xs font-medium transition-colors"
                style={{
                  background: isActive
                    ? (isTout ? 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))' : 'var(--color-gold)')
                    : 'var(--bg-tertiary)',
                  color: isActive ? (isTout ? 'white' : 'var(--color-black)') : 'var(--text-muted)',
                  border: isActive ? 'none' : '1px solid var(--border-dark)',
                }}>
                {c.label}
              </button>
            );
          })}
        </div>
        <div className="flex gap-1">
          {MARKET_TYPES.map(m => {
            const isActive = selectedMarket === m.id;
            let bg = 'var(--bg-tertiary)';
            let color = 'var(--text-muted)';
            let border = '1px solid var(--border-dark)';
            if (isActive) {
              border = 'none';
              if (m.id === 'all') {
                bg = 'linear-gradient(135deg, #b8942e, #d4a843)';
                color = '#111';
              } else if (m.id === 'white') {
                bg = '#ffffff';
                color = '#111';
              } else if (m.id === 'black') {
                bg = '#000000';
                color = '#ffffff';
              }
            }
            return (
              <button key={m.id} onClick={() => setSelectedMarket(m.id)}
                className="px-3 py-2 rounded-lg text-xs font-medium transition-colors"
                style={{ background: bg, color, border }}>
                {m.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* Loading */}
      {loading && (
        <div className="text-center py-12">
          <div className="w-6 h-6 border-2 border-t-transparent rounded-full animate-spin mx-auto mb-2" style={{ borderColor: 'var(--color-gold)', borderTopColor: 'transparent' }} />
          <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Chargement des annonces...</p>
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="text-center py-8">
          <p className="text-xs mb-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
          <button onClick={loadListings} className="text-xs underline" style={{ color: 'var(--color-gold)' }}>Réessayer</button>
        </div>
      )}

      {/* Results */}
      {!loading && !error && (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map(listing => (
            <div key={listing.id}
              className="panel-glass rounded-xl p-4 hover:scale-[1.02] transition-all cursor-pointer relative"
              style={{ opacity: listing.status === 'reserved' ? 0.5 : 1 }}
            >
              {listing.status === 'reserved' && (
                <div className="absolute top-2 right-2 px-2 py-0.5 rounded text-[9px] font-bold"
                  style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>
                  RÉSERVÉ
                </div>
              )}
              {listing.market_type === 'black' && (
                <div className="absolute top-2 left-2 px-2 py-0.5 rounded text-[9px] font-bold"
                  style={{ background: 'var(--color-red-dark)', color: 'white' }}>
                  MARCHÉ NOIR
                </div>
              )}
              <div className="flex items-start gap-2 mt-4 mb-1">
                {listing.status === 'open' && (
                  <div className="mt-0.5">
                    <DealSelectButton listing={{
                      id: listing.id,
                      title: listing.title,
                      category: listing.category,
                      value: listing.suggested_value,
                      seller: listing.seller?.id || '',
                    }} />
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <h3 className="font-bold text-sm" style={{ color: 'var(--text-primary)' }}>{listing.title}</h3>
                  <p className="text-[10px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
                    {listing.category.replace(/_/g, ' ')} • par {listing.seller?.username || 'Inconnu'}
                  </p>
                </div>
              </div>
              <div className="flex justify-between items-center mt-2">
                <span className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>
                  ∞ {listing.suggested_value.toLocaleString()}
                </span>
                <button className="px-3 py-1 rounded text-xs font-bold transition-all hover:scale-105"
                  style={{ background: 'var(--bg-tertiary)', color: 'var(--color-gold)', border: '1px solid var(--border-gold)' }}>
                  Négocier
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {!loading && !error && filtered.length === 0 && (
        <div className="text-center py-12">
          <p style={{ color: 'var(--text-muted)' }}>Aucune annonce trouvée</p>
        </div>
      )}
    </div>
  );
}
