<commit_before>import { SaleLotsList_saleArtworksConnection } from "__generated__/SaleLotsList_saleArtworksConnection.graphql"
import { OrderedSaleArtworkSorts } from "lib/Components/ArtworkFilterOptions/SortOptions"
import { FilteredArtworkGridZeroState } from "lib/Components/ArtworkGrids/FilteredArtworkGridZeroState"
import { InfiniteScrollArtworksGridContainer } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid"
import { ArtworkFilterContext } from "lib/utils/ArtworkFilter/ArtworkFiltersStore"
import { filterArtworksParams, FilterParamName, ViewAsValues } from "lib/utils/ArtworkFilter/FilterArtworksHelpers"
import { Schema } from "lib/utils/track"
import { Box, color, Flex, Sans } from "palette"
import React, { useCallback, useContext, useEffect, useState } from "react"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import { useTracking } from "react-tracking"
import styled from "styled-components/native"
import { FilterParams } from "../../../utils/ArtworkFilter/FilterArtworksHelpers"
import { SaleArtworkListContainer } from "./SaleArtworkList"

interface Props {
  saleArtworksConnection: SaleLotsList_saleArtworksConnection
  relay: RelayPaginationProp
  saleID: string
  saleSlug: string
  scrollToTop: () => void
}

export const SaleLotsListSortMode = ({
  filterParams,
  filteredTotal,
  totalCount,
}: {
  filterParams: FilterParams
  filteredTotal: number | null | undefined
  totalCount: number | null | undefined
}) => {
  const getSortDescription = useCallback(() => {
    const sortMode = OrderedSaleArtworkSorts.find((sort) => sort.paramValue === filterParams?.sort)
    if (sortMode) {
      return sortMode.displayText
    }
  }, [filterParams])

  return (
    <Flex px={2} mb={2}>
      <FilterTitle size="4" ellipsizeMode="tail">
        Sorted by {getSortDescription()?.toLowerCase()}
      </FilterTitle>

      {!!filteredTotal && !!totalCount && (
        <FilterDescription size="3t">{`Showing ${filteredTotal} of ${totalCount}`}</FilterDescription>
      )}
    </Flex>
  )
}

export const SaleLotsList: React.FC<Props> = ({ saleArtworksConnection, relay, saleID, saleSlug, scrollToTop }) => {
  const { state, dispatch } = useContext(ArtworkFilterContext)
  const [totalCount, setTotalCount] = useState<number | null>(null)
  const tracking = useTracking()

  const filterParams = filterArtworksParams(state.appliedFilters, state.filterType)
  const viewAsFilter = state.appliedFilters.find((filter) => filter.paramName === FilterParamName.viewAs)
  const counts = saleArtworksConnection.saleArtworksConnection?.counts

  useEffect(() => {
    dispatch({
      type: "setFilterType",
      payload: "saleArtwork",
    })
  }, [])

  useEffect(() => {
    setTotalCount(saleArtworksConnection.saleArtworksConnection?.counts?.total || 0)
  }, [])

  useEffect(() => {
    if (state.applyFilters) {
      // Add the new medium to geneIDs array
      const medium: string[] = []
      if (typeof filterParams.medium === "string") {
        medium.push(filterParams.medium)
      }

      relay.refetchConnection(
        10,
        (error) => {
          if (error) {
            throw new Error("Sale/SaleLotsList filter error: " + error.message)
          }
        },
        {
          ...filterParams,
          saleID: saleSlug,
          geneIDs: medium,
          includeArtworksByFollowedArtists: !!filterParams.includeArtworksByFollowedArtists,
        }
      )
      scrollToTop()
    }
  }, [state.appliedFilters])

  useEffect(() => {
    dispatch({
      type: "setAggregations",
      payload: saleArtworksConnection.saleArtworksConnection?.aggregations,
    })
  }, [])

  useEffect(() => {
    if (saleArtworksConnection.saleArtworksConnection?.counts) {
      dispatch({
        type: "setFilterCounts",
        payload: saleArtworksConnection.saleArtworksConnection?.counts,
      })
    }
  }, [])

  const trackClear = (id: string, slug: string) => {
    tracking.trackEvent({
      action_name: "clearFilters",
      context_screen: Schema.ContextModules.Auction,
      context_screen_owner_type: Schema.OwnerEntityTypes.Auction,
      context_screen_owner_id: id,
      context_screen_owner_slug: slug,
      action_type: Schema.ActionTypes.Tap,
    })
  }

  if (!saleArtworksConnection.saleArtworksConnection?.edges?.length) {
    return (
      <Box my="80px">
        <FilteredArtworkGridZeroState id={saleID} slug={saleSlug} trackClear={trackClear} />
      </Box>
    )
  }

  return (
    <Flex flex={1} my={4}>
      <SaleLotsListSortMode filterParams={filterParams} filteredTotal={counts?.total} totalCount={totalCount} />

      {viewAsFilter?.paramValue === ViewAsValues.List ? (
        <SaleArtworkListContainer
          connection={saleArtworksConnection.saleArtworksConnection!}
          hasMore={relay.hasMore}
          loadMore={relay.loadMore}
          isLoading={relay.isLoading}
        />
      ) : (
        <Flex px={2}>
          <InfiniteScrollArtworksGridContainer
            connection={saleArtworksConnection.saleArtworksConnection!}
            hasMore={relay.hasMore}
            loadMore={relay.loadMore}
            showLotLabel
            hidePartner
            hideUrgencyTags
          />
        </Flex>
      )}
    </Flex>
  )
}

export const FilterTitle = styled(Sans)``
export const FilterDescription = styled(Sans)`<commit_msg>fix(SaleLotsList): grid disappears after the user registers (#4082)<commit_after>import { SaleLotsList_saleArtworksConnection } from "__generated__/SaleLotsList_saleArtworksConnection.graphql"
import { OrderedSaleArtworkSorts } from "lib/Components/ArtworkFilterOptions/SortOptions"
import { FilteredArtworkGridZeroState } from "lib/Components/ArtworkGrids/FilteredArtworkGridZeroState"
import { InfiniteScrollArtworksGridContainer } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid"
import { ArtworkFilterContext } from "lib/utils/ArtworkFilter/ArtworkFiltersStore"
import { filterArtworksParams, FilterParamName, ViewAsValues } from "lib/utils/ArtworkFilter/FilterArtworksHelpers"
import { Schema } from "lib/utils/track"
import { Box, color, Flex, Sans } from "palette"
import React, { useCallback, useContext, useEffect, useState } from "react"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import { useTracking } from "react-tracking"
import styled from "styled-components/native"
import { FilterParams } from "../../../utils/ArtworkFilter/FilterArtworksHelpers"
import { SaleArtworkListContainer } from "./SaleArtworkList"

interface Props {
  saleArtworksConnection: SaleLotsList_saleArtworksConnection
  relay: RelayPaginationProp
  saleID: string
  saleSlug: string
  scrollToTop: () => void
}

export const SaleLotsListSortMode = ({
  filterParams,
  filteredTotal,
  totalCount,
}: {
  filterParams: FilterParams
  filteredTotal: number | null | undefined
  totalCount: number | null | undefined
}) => {
  const getSortDescription = useCallback(() => {
    const sortMode = OrderedSaleArtworkSorts.find((sort) => sort.paramValue === filterParams?.sort)
    if (sortMode) {
      return sortMode.displayText
    }
  }, [filterParams])

  return (
    <Flex px={2} mb={2}>
      <FilterTitle size="4" ellipsizeMode="tail">
        Sorted by {getSortDescription()?.toLowerCase()}
      </FilterTitle>

      {!!filteredTotal && !!totalCount && (
        <FilterDescription size="3t">{`Showing ${filteredTotal} of ${totalCount}`}</FilterDescription>
      )}
    </Flex>
  )
}

export const SaleLotsList: React.FC<Props> = ({ saleArtworksConnection, relay, saleID, saleSlug, scrollToTop }) => {
  const { state, dispatch } = useContext(ArtworkFilterContext)
  const [totalCount, setTotalCount] = useState<number | null>(null)
  const tracking = useTracking()

  const filterParams = filterArtworksParams(state.appliedFilters, state.filterType)
  const viewAsFilter = state.appliedFilters.find((filter) => filter.paramName === FilterParamName.viewAs)
  const counts = saleArtworksConnection.saleArtworksConnection?.counts

  useEffect(() => {
    dispatch({
      type: "setFilterType",
      payload: "saleArtwork",
    })
  }, [])

  useEffect(() => {
    setTotalCount(saleArtworksConnection.saleArtworksConnection?.counts?.total || 0)
  }, [])

  useEffect(() => {
    if (state.applyFilters) {
      // Add the new medium to geneIDs array
      const medium: string[] = []
      if (typeof filterParams.medium === "string") {
        medium.push(filterParams.medium)
      }

      relay.refetchConnection(
        10,
        (error) => {
          if (error) {
            throw new Error("Sale/SaleLotsList filter error: " + error.message)
          }
        },
        {
          ...filterParams,
          saleID: saleSlug,
          geneIDs: medium,
          includeArtworksByFollowedArtists: !!filterParams.includeArtworksByFollowedArtists,
        }
      )
      scrollToTop()
    }
  }, [state.appliedFilters])

  useEffect(() => {
    dispatch({
      type: "setAggregations",
      payload: saleArtworksConnection.saleArtworksConnection?.aggregations,
    })
  }, [])

  useEffect(() => {
    if (saleArtworksConnection.saleArtworksConnection?.counts) {
      dispatch({
        type: "setFilterCounts",
        payload: saleArtworksConnection.saleArtworksConnection?.counts,
      })
    }
  }, [])

  const trackClear = (id: string, slug: string) => {
    tracking.trackEvent({
      action_name: "clearFilters",
      context_screen: Schema.ContextModules.Auction,
      context_screen_owner_type: Schema.OwnerEntityTypes.Auction,
      context_screen_owner_id: id,
      context_screen_owner_slug: slug,
      action_type: Schema.ActionTypes.Tap,
    })
  }

  if (!saleArtworksConnection.saleArtworksConnection?.edges?.length) {
    return (
      <Box my="80px">
        <FilteredArtworkGridZeroState id={saleID} slug={saleSlug} trackClear={trackClear} />
      </Box>
    )
  }

  return (
    <Flex flex={0} my={4}>
      <SaleLotsListSortMode filterParams={filterParams} filteredTotal={counts?.total} totalCount={totalCount} />

      {viewAsFilter?.paramValue === ViewAsValues.List ? (
        <SaleArtworkListContainer
          connection={saleArtworksConnection.saleArtworksConnection!}
          hasMore={relay.hasMore}
          loadMore={relay.loadMore}
          isLoading={relay.isLoading}
        />
      ) : (
        <Flex px={2}>
          <InfiniteScrollArtworksGridContainer
            connection={saleArtworksConnection.saleArtworksConnection!}
            hasMore={relay.hasMore}
            loadMore={relay.loadMore}
            showLotLabel
            hidePartner
            hideUrgencyTags
          />
        </Flex>
      )}
    </Flex>
  )
}

export const FilterTitle = styled(Sans)``
export const FilterDescription = styled(Sans)`
{'fraction_non_alphanumeric': 0.11625761210555453, 'fraction_numerical': 0.002583502491234545, 'mean_word_length': 3.493781094527363, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 65, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4433509', 'n_tokens_mistral': 3246, 'n_tokens_neox': 3178, 'n_words': 574}