import { Contract } from 'web/lib/firebase/contracts'
import { User } from 'web/lib/firebase/users'
import { Col } from '../layout/col'
import { SiteLink } from '../site-link'
import { ContractCard } from './contract-card'
import { ShowTime } from './contract-details'
import { ContractSearch } from '../contract-search'
import { useCallback } from 'react'
import clsx from 'clsx'
import { LoadingIndicator } from '../loading-indicator'
import { VisibilityObserver } from '../visibility-observer'

export type ContractHighlightOptions = {
  contractIds?: string[]
  highlightClassName?: string
}

export function ContractsGrid(props: {
  contracts: Contract[] | undefined
  loadMore?: () => void
  showTime?: ShowTime
  onContractClick?: (contract: Contract) => void
  gridClassName?: string
  cardHideOptions?: {
    hideQuickBet?: boolean
    hideGroupLink?: boolean
  }
  highlightOptions?: ContractHighlightOptions
}) {
  const {
    contracts,
    showTime,
    loadMore,
    onContractClick,
    gridClassName,
    cardHideOptions,
    highlightOptions,
  } = props
  const { hideQuickBet, hideGroupLink } = cardHideOptions || {}
  const { contractIds, highlightClassName } = highlightOptions || {}
  const onVisibilityUpdated = useCallback(
    (visible) => {
      if (visible && loadMore) {
        loadMore()
      }
    },
    [loadMore]
  )

  if (contracts === undefined) {
    return <LoadingIndicator />
  }

  if (contracts.length === 0) {
    return (
      <p className="mx-2 text-gray-500">
        No markets found. Why not{' '}
        <SiteLink href="/create" className="font-bold text-gray-700">
          create one?
        </SiteLink>
      </p>
    )
  }
  // Reorganize the contracts so that the masonry layout shows them in the original order
  // E.g. from [0, 1, 2, 3] => [0, 2, 1, 3]
  // E.g. from [0, 1, 2, 3, 4, 5, 6] => [0, 2, 4, 1, 3, 5, 6]
  const halfway = Math.floor(contracts.length / 2)
  function reorder(i: number) {
    return i < halfway
      ? i * 2
      : Math.min((i - halfway) * 2 + 1, (contracts?.length ?? 1) - 1)
  }
  const twoColContracts = Array.from(
    { length: contracts.length },
    (_, i) => contracts[reorder(i)]
  )

  return (
    <Col className="gap-8">
      <div
        className={clsx(
          'hidden w-full gap-4 space-y-4 md:block md:columns-2',
          gridClassName
        )}
      >
        {twoColContracts.map((contract) => (
          <ContractCard
            contract={contract}
            key={contract.id}
            showTime={showTime}
            onClick={
              onContractClick ? () => onContractClick(contract) : undefined
            }
            hideQuickBet={hideQuickBet}
            hideGroupLink={hideGroupLink}
            className={clsx(
              'break-inside-avoid-column',
              contractIds?.includes(contract.id) && highlightClassName
            )}
          />
        ))}
      </div>
      <div
        className={clsx(
          'w-full columns-1 gap-4 space-y-4 md:hidden',
          gridClassName
        )}
      >
        {contracts.map((contract) => (
          <ContractCard
            contract={contract}
            key={contract.id}
            showTime={showTime}
            onClick={
              onContractClick ? () => onContractClick(contract) : undefined
            }
            hideQuickBet={hideQuickBet}
            hideGroupLink={hideGroupLink}
            className={clsx(
              'break-inside-avoid-column',
              contractIds?.includes(contract.id) && highlightClassName
            )}
          />
        ))}
      </div>
      <VisibilityObserver
        onVisibilityUpdated={onVisibilityUpdated}
        className="relative -top-96 h-1"
      />
    </Col>
  )
}

export function CreatorContractsList(props: {
  user: User | null | undefined
  creator: User
}) {
  const { user, creator } = props

  return (
    <ContractSearch
      user={user}
      defaultSort="newest"
      defaultFilter="all"
      additionalFilter={{
        creatorId: creator.id,
      }}
    />
  )
}
