import { DateFilter, FilterValue, NumberFilter, SortItem, StringFilter } from '@types'

import { ArrowDownAZIcon, ArrowDownZAIcon, FilterIcon } from 'lucide-react'

import { cn } from '@lib/utils'

function hasActiveFilterValue(obj: Record<string, unknown>, key: string): boolean {
  const val = obj[key]
  if (val === undefined) {
    return false
  }
  if (Array.isArray(val)) {
    return val.length > 0
  }
  return val != null && val !== ''
}

const FILTER_KEYS = ['values', 'min', 'max', 'start', 'end', 'contains', 'startsWith', 'endsWith', 'exclude'] as const

function isObjectFilterActive(obj: NumberFilter | DateFilter | StringFilter): boolean {
  return FILTER_KEYS.some((key) => hasActiveFilterValue(obj as Record<string, unknown>, key))
}

function isFilterActive(filterValue: FilterValue): boolean {
  if (filterValue == null) {
    return false
  }
  if (Array.isArray(filterValue)) {
    return filterValue.length > 0
  }
  if (typeof filterValue === 'object') {
    return isObjectFilterActive(filterValue)
  }
  return false
}

export const ColumnHeaderStateIcon = ({
  filterValue,
  sortState,
}: {
  filterValue: FilterValue
  sortState: SortItem | undefined
}) => {
  const hasFilter = isFilterActive(filterValue)
  const sortDir = sortState?.direction ?? null
  const SortIcon = sortDir === 'desc' ? ArrowDownZAIcon : ArrowDownAZIcon

  return (
    <>
      {hasFilter && (
        <FilterIcon
          className={cn(
            'absolute top-1/2 pointer-events-none text-muted-foreground/60 translate-y-[calc(-50%-2.5px)] right-[16.5px] size-4',
            {
              'translate-y-[calc(-50%-3px)] right-6 size-3.25': sortDir,
            },
          )}
        />
      )}
      {sortDir && (
        <SortIcon
          className={cn(
            'absolute top-1/2 pointer-events-none text-muted-foreground/60 translate-y-[calc(-50%+1px)] right-[21px] size-4',
            {
              'translate-y-[calc(-50%+5px)] right-[17.5px] size-3.25': hasFilter,
            },
          )}
        />
      )}
    </>
  )
}
