import { sortBy, debounce } from 'lodash'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { Group } from 'common/group'
import { CreateGroupButton } from 'web/components/groups/create-group-button'
import { Col } from 'web/components/layout/col'
import { Row } from 'web/components/layout/row'
import { Page } from 'web/components/page'
import { Title } from 'web/components/title'
import { UserLink } from 'web/components/user-page'
import { useGroups, useMemberGroupIds } from 'web/hooks/use-group'
import { useUser } from 'web/hooks/use-user'
import { groupPath, listAllGroups } from 'web/lib/firebase/groups'
import { getUser, User } from 'web/lib/firebase/users'
import { Tabs } from 'web/components/layout/tabs'
import { GroupMembersList } from 'web/pages/group/[...slugs]'
import { checkAgainstQuery } from 'web/hooks/use-sort-and-query-params'
export async function getStaticProps() {
const groups = await listAllGroups().catch((_) => [])
const creators = await Promise.all(
groups.map((group) => getUser(group.creatorId))
)
const creatorsDict = Object.fromEntries(
creators.map((creator) => [creator.id, creator])
)
return {
props: {
groups: groups,
creatorsDict,
},
revalidate: 60, // regenerate after a minute
}
}
export default function Groups(props: {
groups: Group[]
creatorsDict: { [k: string]: User }
}) {
const [creatorsDict, setCreatorsDict] = useState(props.creatorsDict)
const groups = useGroups() ?? props.groups
const user = useUser()
const memberGroupIds = useMemberGroupIds(user) || []
useEffect(() => {
// Load User object for creator of new Groups.
const newGroups = groups.filter(({ creatorId }) => !creatorsDict[creatorId])
if (newGroups.length > 0) {
Promise.all(newGroups.map(({ creatorId }) => getUser(creatorId))).then(
(newUsers) => {
const newUsersDict = Object.fromEntries(
newUsers.map((user) => [user.id, user])
)
setCreatorsDict({ ...creatorsDict, ...newUsersDict })
}
)
}
}, [creatorsDict, groups])
const [query, setQuery] = useState('')
// List groups with the highest question count, then highest member count
// TODO use find-active-contracts to sort by?
const matches = sortBy(groups, [
(group) => -1 * group.contractIds.length,
(group) => -1 * group.memberIds.length,
]).filter(
(g) =>
checkAgainstQuery(query, g.name) ||
checkAgainstQuery(query, g.about || '') ||
checkAgainstQuery(query, creatorsDict[g.creatorId].username)
)
const matchesOrderedByRecentActivity = sortBy(groups, [
(group) => -1 * group.mostRecentActivityTime,
]).filter(
(g) =>
checkAgainstQuery(query, g.name) ||
checkAgainstQuery(query, g.about || '') ||
checkAgainstQuery(query, creatorsDict[g.creatorId].username)
)
// Not strictly necessary, but makes the "hold delete" experience less laggy
const debouncedQuery = debounce(setQuery, 50)
return (