"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

export interface VendorProductsSortLabels {
  label: string;
  mostPopular: string;
  bestRating: string;
  newest: string;
  priceLowHigh: string;
  priceHighLow: string;
}

const SORT_VALUES = [
  "popular",
  "rating",
  "createdAt",
  "price-asc",
  "price-desc",
] as const;

/**
 * Sort control for the products toolbar.
 *
 * Sorting used to sit in the filter sidebar as a radio list. It is not a filter,
 * and buyers look for it next to the result count — so it lives here, and the
 * sidebar renders with `showSort={false}`.
 *
 * Writes only `sortBy`, preserving every other search param, so changing the
 * sort never silently clears an active category or price filter.
 */
export function VendorProductsSort({
  currentSort = "popular",
  labels,
}: {
  currentSort?: string;
  labels: VendorProductsSortLabels;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const value = (SORT_VALUES as readonly string[]).includes(currentSort)
    ? currentSort
    : "popular";

  const handleChange = (next: string) => {
    const params = new URLSearchParams(searchParams.toString());
    if (next === "popular") {
      params.delete("sortBy");
    } else {
      params.set("sortBy", next);
    }
    params.delete("page");
    const query = params.toString();
    router.push(query ? `${pathname}?${query}` : pathname);
  };

  return (
    <div className="flex items-center gap-2">
      <span className="hidden shrink-0 text-sm text-muted-foreground sm:inline">
        {labels.label}
      </span>
      <Select value={value} onValueChange={handleChange}>
        <SelectTrigger className="h-9 w-[172px]" aria-label={labels.label}>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="popular">{labels.mostPopular}</SelectItem>
          <SelectItem value="rating">{labels.bestRating}</SelectItem>
          <SelectItem value="createdAt">{labels.newest}</SelectItem>
          <SelectItem value="price-asc">{labels.priceLowHigh}</SelectItem>
          <SelectItem value="price-desc">{labels.priceHighLow}</SelectItem>
        </SelectContent>
      </Select>
    </div>
  );
}
