'use client';
import { useState } from 'react';
import { Icon } from '@/lib/icons';
import { CITIES, CATS } from '@/lib/data';
import { useGo } from '@/lib/router';

type SearchBarProps = {
  compact?: boolean;
  defaultQ?: string;
  defaultCity?: string;
  onSearch?: (v: { q: string; city: string }) => void;
};

export function SearchBar({ compact, defaultQ = '', defaultCity = 'Alger', onSearch }: SearchBarProps) {
  const { go } = useGo();
  const [q, setQ] = useState(defaultQ);
  const [city, setCity] = useState(defaultCity);
  const submit = () => (onSearch ? onSearch({ q, city }) : go('search', { q, city }));
  return (
    <div className="searchbar" style={compact ? { boxShadow: 'var(--sh-sm)' } : undefined}>
      <div className="sb-seg">
        <Icon name="search" size={19} stroke={1.8} />
        <input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Restaurant, salon, café…"
          onKeyDown={(e) => e.key === 'Enter' && submit()}
        />
      </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
          value={city}
          onChange={(e) => setCity(e.target.value)}
          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' }} onClick={submit}>
        <Icon name="search" size={17} stroke={2.2} /><span className="hide-m">Rechercher</span>
      </button>
    </div>
  );
}

export function CategoryChips({ active, onPick }: { active?: string; onPick?: (k: string) => void }) {
  const { go } = useGo();
  return (
    <div className="row wrapf gap12">
      {CATS.map((c) => (
        <div
          key={c.key}
          className={'chip ' + (active === c.key ? 'active' : '')}
          onClick={() => (onPick ? onPick(c.key) : go('category', { cat: c.key }))}
        >
          <Icon name={c.icon} size={16} stroke={1.8} />{c.name}
        </div>
      ))}
    </div>
  );
}
