"use client";

import { useRouter, useSearchParams } from "next/navigation";

import { ActiveFilterChips } from "@/components/active-filter-chips";
import { FilterSidebar } from "@/components/filter-sidebar";
import { ItemGrid } from "@/components/item-grid";
import { NoResults } from "@/components/no-results";
import { Pagination } from "@/components/pagination";
import { SortDropdown } from "@/components/sort-dropdown";
import { Button } from "@/components/ui/button";
import type { ItemSearchSort } from "@/lib/item-search-params";
import { buildItemSearchUrl, parseItemSearchParams } from "@/lib/item-search-params";
import { useItemSearch } from "@/lib/queries/use-item-search";

interface CategoryNode {
  id: number;
  name: string;
  slug: string;
  children: CategoryNode[];
}

interface ItemBrowseClientProps {
  categoryTree: CategoryNode[];
}

export function ItemBrowseClient({ categoryTree }: ItemBrowseClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const params = parseItemSearchParams(searchParams);
  const { data: response, isLoading, isError, refetch } = useItemSearch(params);

  const items = response?.data ?? [];
  const meta = response?.meta;
  const facets = response?.facets ?? {};

  // Map ItemSummary[] to the shape ItemGrid expects
  const gridItems = items.map((item) => ({
    id: item.id ?? "",
    title: item.title ?? "",
    brand: item.brand ?? null,
    price: item.price ?? 0,
    original_retail: null as number | null,
    condition: item.condition ?? "",
    thumbnail_url: item.thumbnail_url ?? null,
    store: {
      id: item.store?.id ?? "",
      name: item.store?.name ?? null,
    },
    // Search hits carry no store rating aggregates; the card hides the badge.
    store_average_rating: null,
    store_review_count: null,
  }));

  function navigate(patch: Partial<Parameters<typeof buildItemSearchUrl>[1]>) {
    router.push(buildItemSearchUrl(params, patch));
  }

  function handleSortChange(sort: ItemSearchSort) {
    navigate({ sort });
  }

  function handlePageChange(page: number) {
    navigate({ page });
  }

  // Error state
  if (isError) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-8">
        <div className="flex flex-col items-center justify-center gap-4 py-16 text-center">
          <h2 className="text-lg font-semibold text-slate-900">
            Something went wrong
          </h2>
          <p className="text-sm text-slate-500">
            We couldn&apos;t load the items. Please try again.
          </p>
          <Button variant="outline" onClick={() => refetch()}>
            Retry
          </Button>
        </div>
      </div>
    );
  }

  const totalPages = meta?.total_pages ?? 0;
  const total = meta?.total ?? 0;

  return (
    <div className="mx-auto max-w-7xl px-4 py-8">
      {/* Top bar: heading + sort */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Browse</h1>
          {!isLoading && (
            <p className="mt-1 text-sm text-slate-500">
              {total.toLocaleString()} {total === 1 ? "item" : "items"}
            </p>
          )}
        </div>
        <SortDropdown
          value={params.sort}
          hasQuery={params.q !== null}
          onChange={handleSortChange}
        />
      </div>

      {/* Active filter chips */}
      <div className="mt-4">
        <ActiveFilterChips params={params} />
      </div>

      {/* Main: sidebar + content */}
      <div className="mt-6 flex gap-8">
        <FilterSidebar
          facets={facets}
          categoryTree={categoryTree}
          params={params}
        />

        <div className="min-w-0 flex-1">
          {isLoading ? (
            <ItemGrid items={[]} isLoading />
          ) : items.length === 0 ? (
            <NoResults />
          ) : (
            <>
              <ItemGrid items={gridItems} />
              <div className="mt-8">
                <Pagination
                  page={params.page}
                  totalPages={totalPages}
                  onChange={handlePageChange}
                />
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
