import { useCallback } from 'react'
import { Box } from '@mui/material'
import { Inbox } from 'lucide-react'
import type { AgentWorkItemFilters } from '../../provider/IAgentWorkItemProvider'
import { useAgentWorkItems } from '../../hooks/useAgentWorkItems'
import { useTeamAgents } from '../../hooks/useTeamAgents'
import { useTeamStore } from '../../stores/teamStore'
import { WorkItemCard } from './WorkItemCard'
import { CardSkeleton, EmptyState, ErrorState } from '../ui'

interface Props {
  filters: AgentWorkItemFilters
  emptyTitle: string
  emptyDescription: string
}

/**
 * Abstand zwischen zwei Vorgängen. Bewusst grosszügig: die Karten tragen kaum
 * noch Farbe, die Trennung übernimmt der Weissraum.
 */
const LIST_GAP = 2.5

export function WorkItemList({ filters, emptyTitle, emptyDescription }: Props) {
  const { data: items = [], isLoading, isError, refetch } = useAgentWorkItems(filters)
  const { data: agents = [] } = useTeamAgents()
  const selectedId = useTeamStore(s => s.selectedWorkItemId)
  const setSelectedId = useTeamStore(s => s.setSelectedWorkItemId)

  // Stabile Referenz, sonst greift React.memo auf WorkItemCard nicht (CLAUDE.md §10.3).
  const handleSelect = useCallback((id: string) => setSelectedId(id), [setSelectedId])

  if (isLoading) {
    return (
      <Box sx={{ p: 3, display: 'grid', gap: LIST_GAP }}>
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
      </Box>
    )
  }

  if (isError) {
    return <ErrorState message="Vorgänge konnten nicht geladen werden." onRetry={() => refetch()} />
  }

  if (items.length === 0) {
    return <EmptyState icon={<Inbox size={36} />} title={emptyTitle} description={emptyDescription} />
  }

  return (
    <Box sx={{ p: 3, display: 'grid', gap: LIST_GAP }}>
      {items.map((item) => (
        <WorkItemCard
          key={item.id}
          item={item}
          agent={agents.find(a => a.id === item.agentId)}
          selected={item.id === selectedId}
          onSelect={handleSelect}
        />
      ))}
    </Box>
  )
}
