'use client';

/**
 * Client component for sort select + pagination on the category page.
 * Uses URL search params so the server component re-renders with fresh data.
 */

import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import Link from 'next/link';

const SORT_OPTIONS = [
  { value: '', label: 'Relevance' },
  { value: 'name-asc', label: 'Name A–Z' },
  { value: 'name-desc', label: 'Name Z–A' },
  { value: 'price-asc', label: 'Price: Low to High' },
  { value: 'price-desc', label: 'Price: High to Low' },
];

interface CategoryControlsProps {
  categoryId: string;
  sort: string;
  page: number;
  totalPages: number;
  total: number;
}

export default function CategoryControls({
  categoryId,
  sort,
  page,
  totalPages,
  total,
}: CategoryControlsProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  function buildUrl(overrides: Record<string, string | number>) {
    const params = new URLSearchParams(searchParams.toString());
    for (const [key, value] of Object.entries(overrides)) {
      if (value === '' || value === 1) {
        params.delete(key);
      } else {
        params.set(key, String(value));
      }
    }
    const qs = params.toString();
    return qs ? `${pathname}?${qs}` : pathname;
  }

  function handleSortChange(e: React.ChangeEvent<HTMLSelectElement>) {
    router.push(buildUrl({ sort: e.target.value, page: 1 }));
  }

  return (
    <>
      {/* Sort Bar */}
      <div className="flex items-center justify-between mb-6 pb-4 border-b border-surface-100">
        <div className="flex items-center gap-3">
          <label htmlFor="sort-select" className="text-sm text-surface-500">
            Sort by:
          </label>
          <select
            id="sort-select"
            value={sort}
            onChange={handleSortChange}
            className="text-sm border border-surface-200 rounded-lg px-3 py-2 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500"
          >
            {SORT_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
        <div className="text-sm text-surface-400" aria-live="polite">
          {total} {total === 1 ? 'product' : 'products'} &mdash; page {page} of {totalPages || 1}
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div
          className="flex items-center justify-center gap-2 mt-10"
          role="navigation"
          aria-label="Pagination"
        >
          <Link
            href={buildUrl({ page: page - 1 })}
            aria-label="Previous page"
            aria-disabled={page === 1}
            className={`px-4 py-2 text-sm font-medium rounded-lg border border-surface-200 hover:bg-surface-50 transition-colors ${
              page === 1 ? 'opacity-40 pointer-events-none' : ''
            }`}
          >
            ← Previous
          </Link>

          {buildPageNumbers(page, totalPages).map((pageNum, i) =>
            pageNum === null ? (
              <span key={`ellipsis-${i}`} className="px-2 text-surface-400">
                …
              </span>
            ) : (
              <Link
                key={pageNum}
                href={buildUrl({ page: pageNum })}
                aria-label={`Page ${pageNum}`}
                aria-current={page === pageNum ? 'page' : undefined}
                className={`w-10 h-10 text-sm font-medium rounded-lg flex items-center justify-center transition-colors ${
                  page === pageNum
                    ? 'bg-brand-500 text-white'
                    : 'border border-surface-200 hover:bg-surface-50'
                }`}
              >
                {pageNum}
              </Link>
            )
          )}

          <Link
            href={buildUrl({ page: page + 1 })}
            aria-label="Next page"
            aria-disabled={page === totalPages}
            className={`px-4 py-2 text-sm font-medium rounded-lg border border-surface-200 hover:bg-surface-50 transition-colors ${
              page === totalPages ? 'opacity-40 pointer-events-none' : ''
            }`}
          >
            Next →
          </Link>
        </div>
      )}
    </>
  );
}

function buildPageNumbers(current: number, total: number): (number | null)[] {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
  const pages: (number | null)[] = [1];
  if (current > 3) pages.push(null);
  for (let p = Math.max(2, current - 1); p <= Math.min(total - 1, current + 1); p++) {
    pages.push(p);
  }
  if (current < total - 2) pages.push(null);
  pages.push(total);
  return pages;
}
