/**
 * ============================================
 * SEARCH RESULTS PAGE
 * ============================================
 * Equivalent to: search/index.html.twig in Shopware
 * Route: /search?q=...
 *
 * Server component — fetches results on the server for fast renders.
 * SearchBar navigates here with the query in the URL.
 */

import { getProducts, ShopwareProduct } from '@/lib/shopware-api';
import ProductCard from '@/components/product/ProductCard';
import Link from 'next/link';
import type { Metadata } from 'next';

const LIMIT = 12;

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}): Promise<Metadata> {
  const { q } = await searchParams;
  return {
    title: q ? `Search results for "${q}"` : 'Search',
  };
}

export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; page?: string }>;
}) {
  const { q, page: pageParam } = await searchParams;
  const query = (q || '').trim();
  const page = Math.max(1, parseInt(pageParam || '1'));

  let products: ShopwareProduct[] = [];
  let total = 0;
  let error: string | null = null;

  if (query.length >= 2) {
    try {
      const result = await getProducts({ search: query, page, limit: LIMIT });
      products = result.elements || [];
      total = result.total || 0;
    } catch (e) {
      error = 'Search failed. Please try again.';
      console.error('Search error:', e);
    }
  }

  const totalPages = Math.ceil(total / LIMIT);

  const buildPageUrl = (p: number) => {
    const params = new URLSearchParams();
    if (query) params.set('q', query);
    if (p > 1) params.set('page', String(p));
    return `/search?${params.toString()}`;
  };

  return (
    <div className="max-w-7xl mx-auto px-6 py-10">
      {/* Breadcrumb */}
      <nav className="text-sm text-surface-400 mb-4 flex items-center gap-1.5">
        <Link href="/" className="hover:text-surface-600 transition-colors">
          Home
        </Link>
        <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
        <span className="text-surface-700 font-medium">Search</span>
      </nav>

      {/* Header */}
      <div className="mb-8">
        <h1 className="text-2xl lg:text-3xl font-bold text-surface-900">
          {query ? (
            <>
              Results for{' '}
              <span className="text-brand-600">&ldquo;{query}&rdquo;</span>
            </>
          ) : (
            'Search'
          )}
        </h1>
        {query && !error && (
          <p className="text-surface-500 mt-1 text-sm">
            {total} {total === 1 ? 'product' : 'products'} found
          </p>
        )}
      </div>

      {/* No query entered */}
      {!query && (
        <div className="text-center py-24">
          <svg
            className="w-16 h-16 mx-auto text-surface-200 mb-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
          <p className="text-surface-400 text-lg">Type something in the search bar above</p>
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-6 text-center mb-8">
          <p className="text-red-600 font-medium">{error}</p>
        </div>
      )}

      {/* Results grid */}
      {products.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {products.map((product, index) => (
            <div
              key={product.id}
              className="animate-slide-up"
              style={{ animationDelay: `${index * 30}ms` }}
            >
              <ProductCard product={product} />
            </div>
          ))}
        </div>
      )}

      {/* No results */}
      {query && !error && products.length === 0 && (
        <div className="text-center py-20">
          <span className="text-5xl mb-4 block">🔍</span>
          <p className="text-surface-500 text-lg mb-2">
            No products found for &ldquo;{query}&rdquo;
          </p>
          <p className="text-surface-400 text-sm mb-6">
            Try a different search term or browse by category
          </p>
          <Link
            href="/"
            className="inline-block px-6 py-2.5 bg-brand-500 hover:bg-brand-600 text-white font-semibold rounded-xl transition-colors"
          >
            Browse Products
          </Link>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex justify-center items-center gap-2 mt-12">
          {page > 1 && (
            <Link
              href={buildPageUrl(page - 1)}
              className="px-4 py-2 border border-surface-200 rounded-lg text-sm hover:border-brand-500 hover:text-brand-600 transition-colors"
            >
              ← Previous
            </Link>
          )}

          {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
            <Link
              key={p}
              href={buildPageUrl(p)}
              className={`px-3.5 py-2 rounded-lg text-sm font-medium transition-colors ${
                p === page
                  ? 'bg-brand-500 text-white'
                  : 'border border-surface-200 hover:border-brand-500 hover:text-brand-600'
              }`}
            >
              {p}
            </Link>
          ))}

          {page < totalPages && (
            <Link
              href={buildPageUrl(page + 1)}
              className="px-4 py-2 border border-surface-200 rounded-lg text-sm hover:border-brand-500 hover:text-brand-600 transition-colors"
            >
              Next →
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
