"use client"

import { useMemo } from "react"
import type { DriveFileInfo } from "@/lib/api/types"
import { useDriveFilterCorpus } from "@/lib/api/hooks/use-drive-queries"
import {
  applyDriveFilters,
  buildDriveFolderPathsWithMatches,
} from "@/lib/drive/drive-filters"
import { sortDriveItems } from "@/lib/drive/drive-sort"
import type { DriveFolderPlacement, DriveSortField } from "@/lib/stores/drive-settings-store"
import {
  driveFiltersActive,
  type DriveFiltersSnapshot,
} from "@/lib/stores/drive-filters-store"
import { filterHiddenDriveSidecars } from "@/lib/drive/drive-hidden-files"

export function useDriveFilteredItems(
  items: DriveFileInfo[],
  filters: DriveFiltersSnapshot,
  sort: {
    sortField: DriveSortField
    sortDir: "asc" | "desc"
    folderPlacement: DriveFolderPlacement
  },
  options?: {
    /** When true, fetch recursive file index under scopePath for folder pruning. */
    recursiveCorpus?: boolean
    scopePath?: string
  }
) {
  const scopePath = options?.scopePath ?? "/"
  const filtersActive = driveFiltersActive(filters)
  const needsRecursiveCorpus = Boolean(options?.recursiveCorpus && filtersActive)
  const corpusQuery = useDriveFilterCorpus(scopePath, needsRecursiveCorpus)

  const visibleItems = useMemo(() => filterHiddenDriveSidecars(items), [items])

  const filteredItems = useMemo(() => {
    if (!filtersActive) {
      return sortDriveItems(visibleItems, sort)
    }

    const filterOptions = needsRecursiveCorpus
      ? corpusQuery.data?.files
        ? {
            folderKeepPaths: buildDriveFolderPathsWithMatches(
              filterHiddenDriveSidecars(corpusQuery.data.files),
              filters,
              scopePath
            ),
          }
        : corpusQuery.isError
          ? { matchCorpus: visibleItems, scopePath }
          : undefined
      : { matchCorpus: visibleItems, scopePath }

    const filtered = applyDriveFilters(visibleItems, filters, filterOptions)
    return sortDriveItems(filtered, sort)
  }, [
    visibleItems,
    filters,
    sort,
    filtersActive,
    needsRecursiveCorpus,
    corpusQuery.data?.files,
    corpusQuery.isError,
    scopePath,
  ])

  const corpusLoading = needsRecursiveCorpus && corpusQuery.isLoading && !corpusQuery.data

  return { filteredItems, corpusLoading, filtersActive }
}
