"use client";

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

import MobileFilterSheet from "./MobileFilterSheet";
import ProductsGrid from "./ProductsGrid";
import type { StoreProduct } from "@/lib/actions/products";
import type { FilterOption } from "./FilterContent";

export default function ProductSection({
  products,
  heading = "All Products",
  categoryOptions = [],
  brandOptions = [],
  parentCategories = [],
}: {
  products: StoreProduct[];
  heading?: string;
  categoryOptions?: FilterOption[];
  brandOptions?: FilterOption[];
  parentCategories?: { slug: string; label: string; hasChildren: boolean }[];
  priceMax?: number;
  currencySymbol?: string;
}) {
  const router = useRouter();
  const searchParams = useSearchParams();

  const currentSort = searchParams.get("sort") ?? "popularity";

  function handleSortChange(value: string | null) {
    if (!value) return;
    const params = new URLSearchParams(searchParams.toString());
    params.set("sort", value);
    router.push(`?${params.toString()}`, { scroll: false });
  }

  return (
    <main className="flex-1 bg-background p-4 sm:p-6 lg:p-8">
      <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight sm:text-3xl">
            {heading}
          </h1>
          <p className="text-sm text-muted-foreground">
            Showing {products.length} product{products.length === 1 ? "" : "s"}
            {products.length > 0
              ? " matching your filters"
              : "; try adjusting your filters"}
          </p>
        </div>

        <div className="flex items-center gap-3">
          <MobileFilterSheet
            categories={categoryOptions}
            brands={brandOptions}
            parentCategories={parentCategories}
          />
          <Select
            items={[
              { value: "popularity", label: "Sort by: Popularity" },
              { value: "price-asc", label: "Price: Low to High" },
              { value: "price-desc", label: "Price: High to Low" },
              { value: "newest", label: "Newest Arrivals" },
            ]}
            value={currentSort}
            onValueChange={handleSortChange}
          >
            <SelectTrigger className="hidden w-50 md:flex">
              <SelectValue placeholder="Sort by" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="popularity">Sort by: Popularity</SelectItem>
              <SelectItem value="price-asc">Price: Low to High</SelectItem>
              <SelectItem value="price-desc">Price: High to Low</SelectItem>
              <SelectItem value="newest">Newest Arrivals</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <ProductsGrid products={products} />
    </main>
  );
}
