import { createListCollection, Flex, Select, Text, Tooltip } from '@chakra-ui/react'
import { ChevronDown } from 'lucide-react'
import { useMemo } from 'react'
import type { SelectRootProps } from '@chakra-ui/react'
import { CalledItAvatar } from '../../components'
import { competitionLogoUrl, type CompetitionResponse } from './competitionApi'
import { formatDate } from '../../utils/dateFormat'

type CompetitionSelectorProps = Omit<SelectRootProps, 'collection'> & {
  competitions: CompetitionResponse[]
  loading: boolean
  competitionIdsWithBets: number[]
}

type Status = 'active' | 'future' | 'past'

function getStatus(comp: CompetitionResponse): Status {
  const now = new Date()
  const start = new Date(comp.startDate)
  const end = new Date(comp.endDate)
  if (now >= start && now <= end) return 'active'
  if (now < start) return 'future'
  return 'past'
}

function sortCompetitions(competitions: CompetitionResponse[]): CompetitionResponse[] {
  const order: Record<Status, number> = { active: 0, future: 1, past: 2 }
  return [...competitions].sort((a, b) => {
    const sa = order[getStatus(a)]
    const sb = order[getStatus(b)]
    if (sa !== sb) return sa - sb
    if (sa === 2)
      return new Date(b.endDate).getTime() - new Date(a.endDate).getTime()
    return new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
  })
}

const statusColor: Record<Status, string> = {
  active: 'var(--chakra-colors-green-500)',
  future: 'var(--chakra-colors-blue-400)',
  past: 'var(--chakra-colors-gray-400)',
}

const statusLabel: Record<Status, string> = {
  active: 'Active — currently ongoing',
  future: 'Upcoming — not started yet',
  past: 'Finished',
}

export function CompetitionSelector({
  competitions,
  loading,
  competitionIdsWithBets,
  ...props
}: CompetitionSelectorProps) {
  const sorted = useMemo(() => sortCompetitions(competitions), [competitions])

  const collection = useMemo(
    () =>
      createListCollection({
        items: sorted,
        itemToValue: (c) => String(c.id),
        itemToString: (c) => c.name,
      }),
    [sorted],
  )

  const betSet = useMemo(() => new Set(competitionIdsWithBets), [competitionIdsWithBets])

  return (
    <Select.Root collection={collection} {...props}>
      <Select.HiddenSelect />
      <Select.Trigger borderColor="border" bg="panel" minW="200px">
        <Select.ValueText placeholder={loading ? 'Loading...' : 'Select competition'} />
        <Select.Indicator>
          <ChevronDown size={16} />
        </Select.Indicator>
      </Select.Trigger>
      <Select.Positioner>
        <Select.Content minW="260px">
          {sorted.map((comp) => {
            const status = getStatus(comp)
            const hasBets = betSet.has(comp.id)
            return (
              <Select.Item key={comp.id} item={comp} py="2">
                <Flex flex="1" align="center" gap="2" minW="0">
                  <CalledItAvatar src={competitionLogoUrl(comp.logoUrl)} name={comp.name} size="xs" flexShrink={0} />
                  {/* Status dot with tooltip */}
                  <Tooltip.Root openDelay={200} closeDelay={0}>
                    <Tooltip.Trigger asChild>
                      <Flex
                        flexShrink={0}
                        w="2"
                        h="2"
                        rounded="full"
                        bg={statusColor[status]}
                        mt="0.5"
                        cursor="default"
                      />
                    </Tooltip.Trigger>
                    <Tooltip.Positioner>
                      <Tooltip.Content>
                        <Tooltip.Arrow><Tooltip.ArrowTip /></Tooltip.Arrow>
                        {statusLabel[status]}
                      </Tooltip.Content>
                    </Tooltip.Positioner>
                  </Tooltip.Root>
                  <Flex direction="column" minW="0" flex="1">
                    <Flex align="center" gap="2">
                      <Select.ItemText fontWeight="600" color="heading" truncate>
                        {comp.name}
                      </Select.ItemText>
                      {hasBets && (
                        <Flex
                          flexShrink={0}
                          px="1.5"
                          py="0.5"
                          rounded="full"
                          bg="brand.subtle"
                          fontSize="2xs"
                          fontWeight="600"
                          color="brand.fg"
                          lineHeight="1"
                        >
                          bets
                        </Flex>
                      )}
                    </Flex>
                    <Text fontSize="xs" color="muted">
                      {formatDate(comp.startDate)} – {formatDate(comp.endDate)}
                    </Text>
                  </Flex>
                </Flex>
                <Select.ItemIndicator />
              </Select.Item>
            )
          })}
        </Select.Content>
      </Select.Positioner>
    </Select.Root>
  )
}
