'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useMemo, useState } from 'react';
import ProductCard from './ProductCard';
import type { Category, Product } from '@/lib/types';

export default function MenuBrowser({
  categories,
  products,
}: {
  categories: Category[];
  products: Product[];
}) {
  const router = useRouter();
  const params = useSearchParams();
  const active = params.get('kategori') ?? 'tumu';
  const [query, setQuery] = useState('');

  const byCat = useMemo(() => new Map(categories.map((c) => [c.id, c])), [categories]);

  const filtered = useMemo(() => {
    const q = query.trim().toLocaleLowerCase('tr');
    return products.filter((p) => {
      const cat = byCat.get(p.category_id);
      if (active !== 'tumu' && cat?.slug !== active) return false;
      if (!q) return true;
      return (
        p.name.toLocaleLowerCase('tr').includes(q) ||
        (p.description ?? '').toLocaleLowerCase('tr').includes(q)
      );
    });
  }, [products, byCat, active, query]);

  const grouped = useMemo(() => {
    const map = new Map<string, Product[]>();
    for (const p of filtered) {
      const list = map.get(p.category_id) ?? [];
      list.push(p);
      map.set(p.category_id, list);
    }
    return categories
      .filter((c) => map.has(c.id))
      .map((c) => ({ category: c, items: map.get(c.id)! }));
  }, [filtered, categories]);

  const setCategory = (slug: string) => {
    const url = slug === 'tumu' ? '/menu' : `/menu?kategori=${slug}`;
    router.replace(url, { scroll: false });
  };

  return (
    <>
      <div className="sticky top-20 z-30 -mx-5 border-b border-cocoa-800/8 bg-cream-50/92 px-5 py-4 backdrop-blur-md sm:-mx-8 sm:px-8">
        <div className="mx-auto flex max-w-page flex-col gap-3 lg:flex-row lg:items-center">
          <div className="flex-1 overflow-x-auto lg:overflow-visible">
            <div className="flex gap-2 pb-1 lg:flex-wrap">
              <Chip label="Tümü" active={active === 'tumu'} onClick={() => setCategory('tumu')} />
              {categories.map((c) => (
                <Chip
                  key={c.id}
                  label={c.name}
                  active={active === c.slug}
                  onClick={() => setCategory(c.slug)}
                />
              ))}
            </div>
          </div>
          <div className="relative lg:w-72">
            <svg
              className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-cocoa-400"
              width="15"
              height="15"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <circle cx="11" cy="11" r="7" />
              <path d="m20 20-3.5-3.5" strokeLinecap="round" />
            </svg>
            <input
              type="search"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Ürün ara…"
              aria-label="Ürün ara"
              className="field pl-10"
            />
          </div>
        </div>
      </div>

      <p className="mt-8 text-sm text-cocoa-500">
        <strong className="font-medium text-cocoa-800">{filtered.length}</strong> ürün listeleniyor
      </p>

      {grouped.length === 0 ? (
        <div className="card mt-8 p-14 text-center">
          <p className="font-display text-2xl">Aramanıza uygun ürün bulunamadı</p>
          <p className="mt-2 text-sm text-cocoa-500">
            Farklı bir kelime deneyin ya da tüm kategorilere göz atın.
          </p>
          <button
            type="button"
            onClick={() => {
              setQuery('');
              setCategory('tumu');
            }}
            className="btn-outline mt-6"
          >
            Filtreleri temizle
          </button>
        </div>
      ) : (
        <div className="mt-6 space-y-16">
          {grouped.map(({ category, items }) => (
            <section key={category.id} id={category.slug} className="scroll-mt-44">
              <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 border-b border-cocoa-800/10 pb-4">
                <h2 className="font-display text-3xl">{category.name}</h2>
                <span className="text-xs uppercase tracking-wider text-cocoa-400">
                  {items.length} çeşit
                </span>
              </div>
              {category.description && (
                <p className="mt-3 max-w-2xl text-sm leading-relaxed text-cocoa-600/85">
                  {category.description}
                </p>
              )}
              <div className="mt-7 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
                {items.map((p) => (
                  <ProductCard key={p.id} product={p} category={category} />
                ))}
              </div>
            </section>
          ))}
        </div>
      )}

      <div className="card mt-16 flex flex-col items-center gap-4 p-10 text-center sm:flex-row sm:justify-between sm:text-left">
        <div>
          <h3 className="font-display text-2xl">Listede aradığınız ürün yok mu?</h3>
          <p className="mt-1.5 text-sm text-cocoa-600">
            Özel gramaj ve harç talepleriniz için bize yazın.
          </p>
        </div>
        <Link href="/iletisim" className="btn-primary shrink-0">
          İletişime geçin
        </Link>
      </div>
    </>
  );
}

function Chip({
  label,
  active,
  onClick,
}: {
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={active}
      className={`whitespace-nowrap rounded-full border px-4 py-2 text-sm transition-all ${
        active
          ? 'border-cocoa-800 bg-cocoa-800 text-cream-100'
          : 'border-cocoa-800/15 bg-white/70 text-cocoa-600 hover:border-cocoa-800/40 hover:text-cocoa-900'
      }`}
    >
      {label}
    </button>
  );
}
