import { useCallback, useEffect, useMemo, useState } from 'react'
import type { Item } from '../../lib/collector-types'
import { useCollectorItems } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'
import { kindCounts, sortInboxItems } from './inbox-mappers'
import { isSnoozed, loadSnoozes, pruneExpiredSnoozes, saveSnoozes, type SnoozeMap } from './inbox-snooze'
import { useProjectColorOverrides } from './project-settings'
import { InboxEmptyState } from './InboxEmptyState'
import { InboxFilterRail, type InboxKindFilter } from './InboxFilterRail'
import { InboxTriageRow, projectColorMap, SectionCard } from './InboxTriageRow'

function filterByKind(items: Item[], kind: InboxKindFilter): Item[] {
  if (kind === 'all') return items
  return items.filter((item) => item.kind === kind)
}

function visibleItems(items: Item[], kind: InboxKindFilter, snoozes: SnoozeMap, now: number): Item[] {
  return sortInboxItems(
    filterByKind(
      items.filter((item) => !isSnoozed(item.id, snoozes, now)),
      kind,
    ),
  )
}

/** Full inbox triage list — filters, severity sort, project colors, snooze, empty state. */
export function InboxContent() {
  const itemsQuery = useCollectorItems()
  return (
    <CollectorQueryBoundary query={itemsQuery}>
      {(itemsResponse) => <InboxContentBody items={itemsResponse.items} />}
    </CollectorQueryBoundary>
  )
}

function InboxContentBody({ items }: { items: Item[] }) {

  const [kindFilter, setKindFilter] = useState<InboxKindFilter>('all')
  const [snoozes, setSnoozes] = useState<SnoozeMap>(() => loadSnoozes())
  const [colorOverrides] = useProjectColorOverrides()
  const [now, setNow] = useState(() => Date.now())

  useEffect(() => {
    const id = window.setInterval(() => {
      setNow(Date.now())
      setSnoozes((current) => {
        const pruned = pruneExpiredSnoozes(current)
        if (Object.keys(pruned).length !== Object.keys(current).length) saveSnoozes(pruned)
        return pruned
      })
    }, 250)
    return () => window.clearInterval(id)
  }, [])

  const activeItems = useMemo(
    () => items.filter((item) => !isSnoozed(item.id, snoozes, now)),
    [items, snoozes, now],
  )
  const counts = useMemo(() => kindCounts(activeItems), [activeItems])
  const colors = useMemo(() => projectColorMap(items, colorOverrides), [items, colorOverrides])
  const visible = useMemo(() => visibleItems(items, kindFilter, snoozes, now), [items, kindFilter, snoozes, now])

  const handleSnooze = useCallback((itemId: string, until: number) => {
    setSnoozes((current) => {
      const next = { ...current, [itemId]: until }
      saveSnoozes(next)
      return next
    })
  }, [])

  return (
    <div className="flex flex-col gap-3.5">
      <InboxFilterRail
        selected={kindFilter}
        counts={counts}
        total={activeItems.length}
        onSelect={setKindFilter}
      />
      <SectionCard
        title="Inbox"
        action={{ label: `${activeItems.length} actionable · sorted by impact` }}
      >
        {visible.length === 0 ? (
          <InboxEmptyState />
        ) : (
          visible.map((item, index) => (
            <InboxTriageRow
              key={item.id}
              item={item}
              projectHex={item.project ? colors[item.project] : undefined}
              isLast={index === visible.length - 1}
              onSnooze={handleSnooze}
            />
          ))
        )}
      </SectionCard>
    </div>
  )
}
