import { listAllTags, listAllCollections, listAllActresses, listAllStudios, listAllSeries, listAllGenres, listAllTagCategories } from "@/lib/db/queries";
import { FilterBarClient } from "./FilterBarClient";
import type { FilterTabKey, FilterCriteria } from "@/lib/filters";
import type { FilterOption } from "./MultiFilterPopover";
import type { SortKey } from "@/lib/sort";
import type { LibraryView } from "./ViewToggle";

export type FilterContext =
  | { kind: "all" }
  | { kind: "tag"; name: string }
  | { kind: "collection"; id: number; name: string }
  | { kind: "actress"; name: string }
  | { kind: "studio"; name: string }
  | { kind: "series"; name: string }
  | { kind: "genre"; name: string }
  | { kind: "label"; name: string }
  | { kind: "category"; name: string }
  | { kind: "search"; query: string };

export interface FilterBarProps {
  current?: FilterContext;
  criteria: FilterCriteria;
  sort?: SortKey;
  view?: LibraryView;
}

export function FilterBar({ current = { kind: "all" }, criteria, sort, view }: FilterBarProps) {
  const actresses = listAllActresses();
  const studios = listAllStudios();
  const seriesList = listAllSeries();
  const genres = listAllGenres();
  const collections = listAllCollections();
  const tags = listAllTags();
  const categories = listAllTagCategories();

  const options: Record<FilterTabKey, FilterOption[]> = {
    actresses: actresses.map((a) => ({ id: a.id, name: a.name, count: a.count })),
    studios: studios.map((s) => ({ id: s.id, name: s.name, count: s.count })),
    series: seriesList.map((s) => ({ id: s.id, name: s.name, count: s.count })),
    genres: genres.map((g) => ({ id: g.id, name: g.name, count: g.count })),
    collections: collections.map((c) => ({ id: c.id, name: c.name, count: c.count })),
    tags: tags.map((t) => ({ id: t.id, name: t.name, count: t.count })),
    categories: categories.map((c) => ({ id: c.id, name: c.name, count: c.imageCount })),
  };

  return (
    <FilterBarClient
      criteria={criteria}
      options={options}
      isHome={current.kind === "all"}
      showSort={!!sort}
      sort={sort}
      view={view}
    />
  );
}
