'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { products } from '@/lib/data/products';
import { useLanguage } from '@/context/LanguageContext';
import styles from './InstantSearch.module.css';

interface Props {
  onClose?: () => void;
}

export default function InstantSearch({ onClose }: Props) {
  const { language, t } = useLanguage();
  const router = useRouter();
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<typeof products>([]);
  const [open, setOpen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!query.trim() || query.length < 2) { setResults([]); setOpen(false); return; }
    const q = query.toLowerCase();
    const filtered = products.filter(p =>
      p.name.toLowerCase().includes(q) ||
      p.nameAr.includes(q) ||
      p.brand.toLowerCase().includes(q) ||
      p.category.includes(q)
    ).slice(0, 6);
    setResults(filtered);
    setOpen(true);
  }, [query]);

  const go = (slug: string) => {
    router.push(`/products/${slug}`);
    setQuery('');
    setOpen(false);
    onClose?.();
  };

  return (
    <div className={styles.searchWrap}>
      <div className={styles.inputRow}>
        <span className={styles.searchIcon}>🔍</span>
        <input
          ref={inputRef}
          className={styles.input}
          placeholder={t.header.search}
          value={query}
          onChange={e => setQuery(e.target.value)}
          autoComplete="off"
        />
        {query && (
          <button className={styles.clearBtn} onClick={() => { setQuery(''); setOpen(false); }}>✕</button>
        )}
      </div>

      {open && results.length > 0 && (
        <div className={styles.dropdown}>
          {results.map(p => (
            <button key={p.id} className={styles.result} onClick={() => go(p.slug)}>
              <div className={styles.resultIcon}>
                {p.category === 'smartphones' ? '📱' : p.category === 'watches' ? '⌚' : p.category === 'tablets' ? '💻' : p.category === 'gaming' ? '🎮' : '🎧'}
              </div>
              <div className={styles.resultInfo}>
                <div className={styles.resultName}>{language === 'ar' ? p.nameAr : p.name}</div>
                <div className={styles.resultMeta}>{p.brand} • {p.price.toFixed(3)} KWD</div>
              </div>
              {p.discount && <span className="badge badge-orange">-{p.discount}%</span>}
            </button>
          ))}
          <button className={styles.viewAll} onClick={() => { router.push(`/products?q=${query}`); setOpen(false); }}>
            {language === 'ar' ? `عرض جميع النتائج لـ "${query}"` : `View all results for "${query}"`} →
          </button>
        </div>
      )}

      {open && query.length >= 2 && results.length === 0 && (
        <div className={styles.noResults}>
          {language === 'ar' ? 'لا نتائج' : 'No results found'}
        </div>
      )}
    </div>
  );
}
