import React, { useEffect, useMemo, useState } from "react"; import { Platform, Pressable, StyleSheet, Text, TextInput, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Ionicons } from "@expo/vector-icons"; import { router } from "expo-router"; import { Colors } from "@/theme"; import { useDebouncedValue } from "@/features/content/hooks/use-debounced-value"; import { FacetFilterChips } from "../components/FacetFilterChips"; import { FacetPickerModal } from "../components/FacetPickerModal"; import { FacetValueTypeaheadModal } from "../components/FacetValueTypeaheadModal"; import { SearchResultList } from "../components/SearchResultList"; import { SearchScopeModal } from "../components/SearchScopeModal"; import { useFacetedSearch } from "../hooks/use-faceted-search"; import { useSearchCapabilities } from "../hooks/use-search-capabilities"; import type { FacetFilter, FilterLogic, SearchFacetDefinition, SearchScope, } from "../types/search.types"; export interface FacetedSearchScreenProps { mode?: "global" | "module"; fixedModuleCode?: string; fixedModuleName?: string; } function kindsLabel(scope: SearchScope): string { return scope.content_kinds?.length ? scope.content_kinds .map((value) => value.charAt(0).toUpperCase() + value.slice(1)) .join(", ") : "Any type"; } function globalScopeLabel(scope: SearchScope): string { const modules = scope.module_codes?.length ? `${scope.module_codes.length} module${scope.module_codes.length === 1 ? "" : "s"}` : "All modules"; return `${modules} · ${kindsLabel(scope)}`; } export default function FacetedSearchScreen({ mode = "global", fixedModuleCode, fixedModuleName, }: FacetedSearchScreenProps) { const isModuleMode = mode === "module"; const normalizedModuleCode = fixedModuleCode?.trim().toLowerCase() || ""; const fixedModuleCodes = isModuleMode && normalizedModuleCode ? [normalizedModuleCode] : null; // Capabilities are scoped by the fixed module only. Content-kind selection // remains a user-controlled filter, so selecting one kind never removes the // other kinds from the scope chooser. const capabilityScope = useMemo( () => fixedModuleCodes ? { module_codes: fixedModuleCodes, content_kinds: null, } : undefined, [normalizedModuleCode, isModuleMode], ); const capabilities = useSearchCapabilities(capabilityScope); const [query, setQuery] = useState(""); const debouncedQuery = useDebouncedValue(query.trim(), 350); const [scope, setScope] = useState({ module_codes: fixedModuleCodes, content_kinds: null, }); const [filters, setFilters] = useState([]); const [logic, setLogic] = useState("and"); const [scopeVisible, setScopeVisible] = useState(false); const [facetPickerVisible, setFacetPickerVisible] = useState(false); const [selectedFacet, setSelectedFacet] = useState(null); useEffect(() => { if (!isModuleMode || !normalizedModuleCode) return; setScope((current) => ({ ...current, module_codes: [normalizedModuleCode], })); }, [isModuleMode, normalizedModuleCode]); const effectiveScope = useMemo( () => isModuleMode ? { ...scope, module_codes: normalizedModuleCode ? [normalizedModuleCode] : null, } : scope, [isModuleMode, normalizedModuleCode, scope], ); const resolvedModuleName = fixedModuleName?.trim() || capabilities.data?.modules.find( (module) => module.code === normalizedModuleCode, )?.name || "this module"; const search = useFacetedSearch( { scope: effectiveScope, query: debouncedQuery || undefined, filters, filter_logic: logic, sort: { field: debouncedQuery ? "relevance" : "title", direction: debouncedQuery ? "desc" : "asc", }, page_size: 25, }, capabilities.isSuccess && (!isModuleMode || Boolean(normalizedModuleCode)), ); const merged = useMemo(() => { const pages = search.data?.pages ?? []; return { total: pages[0]?.total ?? 0, items: pages.flatMap((page) => page.items), }; }, [search.data]); const facets = capabilities.data?.facets ?? []; const handleScopeChange = (next: SearchScope) => { setScope( isModuleMode ? { ...next, module_codes: normalizedModuleCode ? [normalizedModuleCode] : null, } : next, ); }; return ( router.back()} style={styles.headerButton} > Search {isModuleMode ? ( {resolvedModuleName} ) : null} {isModuleMode ? ( Search within {resolvedModuleName} ) : null} {query ? ( setQuery("")}> ) : null} setScopeVisible(true)} > {isModuleMode ? "Content type" : "Scope"} {isModuleMode ? kindsLabel(effectiveScope) : globalScopeLabel(effectiveScope)} setFacetPickerVisible(true)} > Filter setFilters((current) => current.filter((_, itemIndex) => itemIndex !== index), ) } onClear={() => setFilters([])} /> {capabilities.isError ? ( Unable to load search configuration void capabilities.refetch()}> Retry ) : ( { if (search.hasNextPage && !search.isFetchingNextPage) { void search.fetchNextPage(); } }} onPress={(item) => router.push( `/modules/${encodeURIComponent( item.module_code, )}/${encodeURIComponent( item.template_code, )}/${encodeURIComponent(item.content_id)}` as never, ) } /> )} {capabilities.data ? ( setScopeVisible(false)} showModules={!isModuleMode} fixedModuleName={isModuleMode ? resolvedModuleName : undefined} /> ) : null} setFacetPickerVisible(false)} onSelect={(facet) => { setFacetPickerVisible(false); setSelectedFacet(facet); }} /> setSelectedFacet(null)} onApply={(filter) => setFilters((current) => [...current, filter]) } /> ); } const styles = StyleSheet.create({ safe: { flex: 1, backgroundColor: Colors.white }, header: { minHeight: 64, flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: 16, paddingTop: Platform.OS === "web" ? 14 : 8, paddingBottom: 8, borderBottomWidth: 1, borderBottomColor: "#ECECEC", backgroundColor: Colors.white, }, headerButton: { width: 32, padding: 4 }, headerCenter: { flex: 1, alignItems: "center" }, headerTitle: { fontSize: 18, fontWeight: "800", color: Colors.textPrimary, }, headerContext: { marginTop: 1, maxWidth: "90%", fontSize: 10, fontWeight: "700", color: Colors.textSecondary, }, controls: { padding: 20, paddingBottom: 12, gap: 12, backgroundColor: Colors.white, }, scopeHint: { fontSize: 12, fontWeight: "700", color: Colors.textSecondary, }, searchBox: { flexDirection: "row", alignItems: "center", gap: 8, borderWidth: 1, borderColor: Colors.border, borderRadius: 14, paddingHorizontal: 13, backgroundColor: "#FAFAFA", }, input: { flex: 1, minHeight: 46, fontSize: 14, color: Colors.textPrimary, }, actionRow: { flexDirection: "row", gap: 10 }, action: { flex: 1, minHeight: 48, flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 12, borderWidth: 1, borderColor: Colors.border, borderRadius: 13, }, actionTitle: { fontSize: 10, fontWeight: "800", color: Colors.textSecondary, textTransform: "uppercase", }, actionValue: { marginTop: 1, fontSize: 12, fontWeight: "700", color: Colors.textPrimary, }, addFilter: { minWidth: 92, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 5, borderRadius: 13, backgroundColor: Colors.primary, }, addFilterText: { fontSize: 13, fontWeight: "800", color: Colors.white, }, error: { flex: 1, alignItems: "center", justifyContent: "center", padding: 30, }, errorTitle: { fontSize: 15, fontWeight: "800", color: Colors.textPrimary, }, retry: { marginTop: 10, fontWeight: "700", color: Colors.primary, }, });