'use client';
import { Suspense, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { Icon } from '@/lib/icons';
import { CATS, CITIES, TINTS, catByKey, type Listing } from '@/lib/data';
import { ListingCard } from '@/components/ListingCard';
import { SearchBar } from '@/components/SearchBar';
import { Crumb } from '@/components/Crumb';
import { useGo } from '@/lib/router';

type Filters = {
  cats: Set<string>;
  price: Set<string>;
  area: Set<string>;
  rating: number;
};

function CheckRow({ label, count, on, onClick }: { label: string; count?: number; on: boolean; onClick: () => void }) {
  return (
    <div className="row gap8" style={{ cursor: 'pointer', padding: '5px 0' }} onClick={onClick}>
      <div
        style={{
          width: 19,
          height: 19,
          borderRadius: 6,
          border: '1.5px solid ' + (on ? 'var(--red)' : 'var(--line3)'),
          background: on ? 'var(--red)' : 'transparent',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexShrink: 0,
        }}
      >
        {on && <Icon name="check" size={13} stroke={3} style={{ color: '#fff' }} />}
      </div>
      <span style={{ fontSize: 14, color: 'var(--ink)', fontWeight: on ? 600 : 500, flex: 1 }}>{label}</span>
      {count != null && <span className="tiny">{count}</span>}
    </div>
  );
}

function FiltersPanel({
  f,
  set,
  areas,
  cityLabel,
}: {
  f: Filters;
  set: React.Dispatch<React.SetStateAction<Filters>>;
  areas: string[];
  cityLabel?: string;
}) {
  const toggle = (key: 'cats' | 'price' | 'area', v: string) =>
    set((s) => {
      const cur = new Set(s[key]);
      cur.has(v) ? cur.delete(v) : cur.add(v);
      return { ...s, [key]: cur };
    });
  return (
    <div className="filters">
      <div>
        <div className="filter-h">Catégorie</div>
        {CATS.slice(0, 6).map((c) => (
          <CheckRow key={c.key} label={c.name} count={c.count} on={f.cats.has(c.key)} onClick={() => toggle('cats', c.key)} />
        ))}
      </div>
      <div style={{ height: 1, background: 'var(--line2)' }}></div>
      <div>
        <div className="filter-h">Budget</div>
        <div className="row gap8">
          {['€', '€€', '€€€', '€€€€'].map((p) => (
            <div key={p} className={'chip chip-sm ' + (f.price.has(p) ? 'active' : '')} onClick={() => toggle('price', p)}>{p}</div>
          ))}
        </div>
      </div>
      {areas.length > 0 && (
        <>
          <div style={{ height: 1, background: 'var(--line2)' }}></div>
          <div>
            <div className="filter-h">Quartier{cityLabel ? ` (${cityLabel})` : ''}</div>
            {areas.slice(0, 6).map((n) => (
              <CheckRow key={n} label={n} on={f.area.has(n)} onClick={() => toggle('area', n)} />
            ))}
          </div>
        </>
      )}
      <div style={{ height: 1, background: 'var(--line2)' }}></div>
      <div>
        <div className="filter-h">Note minimum</div>
        <div className="row gap8">
          {[4.5, 4.0, 3.5].map((r) => (
            <div
              key={r}
              className={'chip chip-sm ' + (f.rating === r ? 'active' : '')}
              onClick={() => set((s) => ({ ...s, rating: s.rating === r ? 0 : r }))}
            >
              <Icon name="star" size={13} fill="var(--gold)" style={{ color: 'var(--gold)' }} />{r}+
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Toolbar({
  count,
  view,
  setView,
  sort,
  setSort,
}: {
  count: number;
  view: 'list' | 'map';
  setView: (v: 'list' | 'map') => void;
  sort: string;
  setSort: (v: string) => void;
}) {
  return (
    <div className="between" style={{ marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
      <div className="small">
        <b style={{ color: 'var(--ink)', fontSize: 15 }}>{count} adresses</b> trouvées
      </div>
      <div className="row gap12">
        <div className="input" style={{ padding: '8px 12px', width: 'auto' }}>
          <Icon name="sliders" size={16} />
          <select
            value={sort}
            onChange={(e) => setSort(e.target.value)}
            style={{ border: 'none', background: 'none', outline: 'none', fontWeight: 600, fontSize: 13.5 }}
          >
            <option value="pop">Les plus populaires</option>
            <option value="rate">Mieux notés</option>
            <option value="price">Prix croissant</option>
          </select>
        </div>
        <div className="seg">
          <button className={view === 'list' ? 'on' : ''} onClick={() => setView('list')}>
            <Icon name="grid" size={15} />Liste
          </button>
          <button className={view === 'map' ? 'on' : ''} onClick={() => setView('map')}>
            <Icon name="map" size={15} />Carte
          </button>
        </div>
      </div>
    </div>
  );
}

function MapView({ listings }: { listings: Listing[] }) {
  const [sel, setSel] = useState<number | undefined>(listings[0]?.id);
  const spots: [number, number][] = [
    [18, 32], [44, 22], [66, 44], [30, 62], [78, 66], [54, 74], [12, 78], [88, 30],
  ];
  const d = listings.find((x) => x.id === sel) || listings[0];
  return (
    <div className="map-ph" style={{ height: 560 }}>
      {listings.slice(0, 8).map((l, i) => (
        <div
          key={l.id}
          onClick={() => setSel(l.id)}
          style={{
            position: 'absolute',
            left: spots[i][0] + '%',
            top: spots[i][1] + '%',
            transform: 'translate(-50%,-50%)',
            cursor: 'pointer',
            zIndex: sel === l.id ? 5 : 2,
          }}
        >
          <div
            style={{
              background: sel === l.id ? 'var(--red)' : 'var(--ink)',
              color: '#fff',
              fontWeight: 700,
              fontSize: 12.5,
              padding: '6px 11px',
              borderRadius: 999,
              boxShadow: 'var(--sh-md)',
              whiteSpace: 'nowrap',
            }}
          >
            {l.price} DA
          </div>
        </div>
      ))}
      {d && (
        <div style={{ position: 'absolute', left: 16, bottom: 16, width: 280, maxWidth: 'calc(100% - 32px)' }}>
          <ListingCard d={d} idx={0} />
        </div>
      )}
    </div>
  );
}

function ExploreScreen({ listings }: { listings: Listing[] }) {
  const sp = useSearchParams();
  const { go } = useGo();
  const cat = sp?.get('cat') || undefined;
  const q = sp?.get('q') || '';
  const cityParam = sp?.get('city') || undefined;
  const city = cityParam || 'Alger';
  const catObj = cat ? catByKey(cat) : null;
  const [f, set] = useState<Filters>({
    cats: new Set<string>(cat ? [cat] : []),
    price: new Set<string>(),
    area: new Set<string>(),
    rating: 0,
  });
  const [view, setView] = useState<'list' | 'map'>('list');
  const [sort, setSort] = useState('pop');

  // Neighborhoods available for the selected city (derived from real listings).
  const cityAreas = useMemo(() => {
    const base = cityParam ? listings.filter((l) => l.city === cityParam) : listings;
    return [...new Set(base.map((l) => l.area).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'fr'));
  }, [listings, cityParam]);
  // Reset the neighborhood selection when the city changes (its quartiers differ).
  useEffect(() => {
    set((s) => (s.area.size ? { ...s, area: new Set<string>() } : s));
  }, [cityParam]);

  let res: Listing[] = listings.slice();
  if (cityParam) res = res.filter((l) => l.city === cityParam);
  if (f.cats.size) res = res.filter((l) => f.cats.has(l.cat));
  if (f.price.size) res = res.filter((l) => f.price.has(l.priceLevel));
  if (f.area.size) res = res.filter((l) => f.area.has(l.area));
  if (f.rating) res = res.filter((l) => l.rating >= f.rating);
  if (q) res = res.filter((l) => (l.name + l.catName + l.tags.join(' ')).toLowerCase().includes(q.toLowerCase()));
  if (sort === 'rate') res.sort((a, b) => b.rating - a.rating);
  if (sort === 'price') res.sort((a, b) => parseInt(a.price.replace(/\s/g, '')) - parseInt(b.price.replace(/\s/g, '')));

  return (
    <div className="wrap" style={{ paddingTop: 24, paddingBottom: 40 }}>
      {catObj && cat ? (
        <div
          className="cat-banner"
          style={{ marginBottom: 24, background: `linear-gradient(135deg, ${TINTS[cat][1]}, ${TINTS[cat][0]})` }}
        >
          <div className="cat-banner-ov"></div>
          <div style={{ position: 'relative' }}>
            <Crumb items={[{ label: 'Accueil', go: ['home'] }, { label: 'Catégories' }, { label: catObj.name }]} />
            <h1 className="h1" style={{ color: '#fff', marginTop: 12 }}>
              {catObj.name}{cityParam ? ` à ${cityParam}` : ' en Algérie'}
            </h1>
            <div className="row gap16" style={{ marginTop: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <div className="cat-city-select">
                <Icon name="pin" size={17} stroke={1.9} style={{ color: 'var(--red)' }} />
                <select
                  value={cityParam || ''}
                  onChange={(e) => go('category', { cat, ...(e.target.value ? { city: e.target.value } : {}) })}
                >
                  <option value="">Toutes les villes</option>
                  {CITIES.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
                <Icon name="chevronDown" size={16} stroke={2} style={{ color: 'var(--muted)' }} />
              </div>
              <span style={{ color: 'rgba(255,255,255,0.9)', fontSize: 14.5, fontWeight: 500 }}>
                {res.length} adresse{res.length > 1 ? 's' : ''}{cityParam ? '' : ' · toutes villes'}
              </span>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ marginBottom: 22 }}>
          <Crumb items={[{ label: 'Accueil', go: ['home'] }, { label: 'Villes', go: ['villes'] }, { label: cityParam || 'Explorer' }]} />
          <h1 className="h1" style={{ fontSize: 30, margin: '12px 0 16px' }}>
            {cityParam ? `Commerces à ${cityParam}` : 'Explorer les commerces'}
          </h1>
          <SearchBar
            compact
            defaultQ={q}
            defaultCity={city}
            onSearch={({ q: nq, city: nc }) => go('search', { ...(nq ? { q: nq } : {}), city: nc })}
          />
        </div>
      )}

      <div className="search-layout">
        <FiltersPanel f={f} set={set} areas={cityAreas} cityLabel={cityParam} />
        <div>
          <Toolbar count={res.length} view={view} setView={setView} sort={sort} setSort={setSort} />
          {view === 'list' ? (
            <div className="grid cols-3">{res.map((d, i) => <ListingCard key={d.id} d={d} idx={i} />)}</div>
          ) : (
            <MapView listings={res} />
          )}
          {res.length === 0 && (
            <div className="panel" style={{ textAlign: 'center', padding: 48 }}>
              <Icon name="search" size={32} style={{ color: 'var(--faint)' }} />
              <h3 className="h3" style={{ marginTop: 12 }}>Aucune adresse trouvée</h3>
              <p className="body" style={{ marginTop: 6 }}>Essayez d’élargir vos filtres.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export function ExplorerClient({ listings }: { listings: Listing[] }) {
  return (
    <Suspense fallback={null}>
      <ExploreScreen listings={listings} />
    </Suspense>
  );
}
