'use client';
import { Suspense, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { Icon } from '@/lib/icons';
import { AD_CATS, CITIES, type Ad } from '@/lib/data';
import { AdCard } from '@/components/AdCard';
import { useGo } from '@/lib/router';

function AnnoncesScreen({ ads }: { ads: Ad[] }) {
  const { go } = useGo();
  const sp = useSearchParams();
  const initialCat = sp?.get('cat');
  const [active, setActive] = useState<Set<string>>(new Set(initialCat ? [initialCat] : []));
  const [conds, setConds] = useState<Set<string>>(new Set());
  const [seller, setSeller] = useState<'all' | 'particulier' | 'pro'>('all');
  const [q, setQ] = useState(sp?.get('q') || '');
  const [sort, setSort] = useState<'recent' | 'low' | 'high'>('recent');

  const toggle = (setFn: React.Dispatch<React.SetStateAction<Set<string>>>, v: string) =>
    setFn((s) => {
      const n = new Set(s);
      n.has(v) ? n.delete(v) : n.add(v);
      return n;
    });

  let res: Ad[] = ads.slice();
  if (active.size) res = res.filter((a) => active.has(a.cat));
  if (conds.size) res = res.filter((a) => conds.has(a.cond));
  if (seller !== 'all') res = res.filter((a) => a.seller.t === seller);
  if (q) res = res.filter((a) => (a.title + a.desc).toLowerCase().includes(q.toLowerCase()));
  if (sort === 'low') res.sort((x, y) => parseInt(x.price.replace(/\s/g, '')) - parseInt(y.price.replace(/\s/g, '')));
  if (sort === 'high') res.sort((x, y) => parseInt(y.price.replace(/\s/g, '')) - parseInt(x.price.replace(/\s/g, '')));

  return (
    <div className="wrap" style={{ paddingTop: 24, paddingBottom: 40 }}>
      <div className="between" style={{ marginBottom: 18, flexWrap: 'wrap', gap: 14 }}>
        <div>
          <div className="eyebrow">Marché de l’occasion</div>
          <h1 className="h1" style={{ fontSize: 38, marginTop: 8 }}>Petites annonces</h1>
          <p className="body" style={{ marginTop: 6 }}>Achetez et vendez près de chez vous, partout en Algérie.</p>
        </div>
        <button className="btn btn-red btn-lg" onClick={() => go('post')}>
          <Icon name="plus" size={18} stroke={2.5} />Déposer une annonce
        </button>
      </div>

      <div className="searchbar" style={{ marginBottom: 18 }}>
        <div className="sb-seg">
          <Icon name="search" size={19} stroke={1.8} />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="iPhone, voiture, canapé…" />
        </div>
        <div className="sb-div"></div>
        <div className="sb-seg" style={{ flex: '0 0 auto' }}>
          <Icon name="pin" size={18} stroke={1.8} style={{ color: 'var(--red)' }} />
          <select className="sb-loc" style={{ border: 'none', outline: 'none', background: 'none', fontWeight: 600 }}>
            {CITIES.map((c) => <option key={c}>{c}</option>)}
          </select>
        </div>
        <button className="btn btn-red" style={{ padding: '13px 22px' }}>
          <Icon name="search" size={17} stroke={2.2} /><span className="hide-m">Rechercher</span>
        </button>
      </div>

      <div className="row wrapf gap12" style={{ marginBottom: 22 }}>
        {AD_CATS.map((c) => (
          <div
            key={c.key}
            className={'chip ' + (active.has(c.key) ? 'active' : '')}
            onClick={() => toggle(setActive, c.key)}
          >
            <Icon name={c.icon} size={16} stroke={1.8} />
            {c.name}
            <span style={{ opacity: 0.6, fontWeight: 600 }}>{(c.count / 1000).toFixed(1)}k</span>
          </div>
        ))}
      </div>

      <div className="search-layout">
        <div className="filters">
          <div>
            <div className="filter-h">Prix (DA)</div>
            <div className="row gap8">
              <div className="input" style={{ padding: '9px 11px' }}><input placeholder="Min" style={{ width: '100%' }} /></div>
              <div className="input" style={{ padding: '9px 11px' }}><input placeholder="Max" style={{ width: '100%' }} /></div>
            </div>
          </div>
          <div style={{ height: 1, background: 'var(--line2)' }}></div>
          <div>
            <div className="filter-h">État</div>
            {['Neuf', 'Comme neuf', 'Très bon état', 'Bon état'].map((c) => (
              <div key={c} className="row gap8" style={{ cursor: 'pointer', padding: '5px 0' }} onClick={() => toggle(setConds, c)}>
                <div
                  style={{
                    width: 19,
                    height: 19,
                    borderRadius: 6,
                    border: '1.5px solid ' + (conds.has(c) ? 'var(--red)' : 'var(--line3)'),
                    background: conds.has(c) ? 'var(--red)' : 'transparent',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                  }}
                >
                  {conds.has(c) && <Icon name="check" size={13} stroke={3} style={{ color: '#fff' }} />}
                </div>
                <span style={{ fontSize: 14, fontWeight: conds.has(c) ? 600 : 500 }}>{c}</span>
              </div>
            ))}
          </div>
          <div style={{ height: 1, background: 'var(--line2)' }}></div>
          <div>
            <div className="filter-h">Vendeur</div>
            <div className="seg" style={{ width: '100%' }}>
              {(
                [
                  ['all', 'Tous'],
                  ['particulier', 'Particulier'],
                  ['pro', 'Pro'],
                ] as const
              ).map(([k, l]) => (
                <button
                  key={k}
                  className={seller === k ? 'on' : ''}
                  style={{ flex: 1, justifyContent: 'center' }}
                  onClick={() => setSeller(k)}
                >
                  {l}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div>
          <div className="between" style={{ marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
            <div className="small">
              <b style={{ color: 'var(--ink)', fontSize: 15 }}>{res.length} annonces</b>
            </div>
            <div className="input" style={{ padding: '8px 12px', width: 'auto' }}>
              <Icon name="sliders" size={16} />
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value as any)}
                style={{ border: 'none', background: 'none', outline: 'none', fontWeight: 600, fontSize: 13.5 }}
              >
                <option value="recent">Plus récentes</option>
                <option value="low">Prix croissant</option>
                <option value="high">Prix décroissant</option>
              </select>
            </div>
          </div>
          <div className="grid cols-3">{res.map((d, i) => <AdCard key={d.id} d={d} idx={i} />)}</div>
        </div>
      </div>
    </div>
  );
}

export function AnnoncesClient({ ads }: { ads: Ad[] }) {
  return (
    <Suspense fallback={null}>
      <AnnoncesScreen ads={ads} />
    </Suspense>
  );
}
