import React from 'react'
import { useDispatch } from 'react-redux'

import { EventRecord } from '~/src/types/core'
import { Dispatch } from '~/src/store'
import { QueryMatchedEventRecord } from '~/src/store/selectors/selectFilteredEventList'
import { EventLabel } from '../EventLabel'
import { EventIcon } from '../EventIcon'
import { Timestamp } from '../Timestamp'
import { EventDestinations } from '../EventDestinations'
import { ScreenReaderOnly } from '../styled'
import { QueryMatchPreview } from '../QueryMatchPreview'

import {
  EventListContainer,
  EventListItem,
  EventTypeLabel,
  EventTime,
  EventSummary,
  EventMeta,
  EventAttributes
} from './style'


export type EventListProps = {
  events: (EventRecord | QueryMatchedEventRecord)[]
  selectedEventRecordId: EventRecord['id']
}

export const EventList = ({ events, selectedEventRecordId }: EventListProps) => {
  const {
    ui: { setSelectedEventRecordId }
  } = useDispatch<Dispatch>()

  return (
    <EventListContainer aria-label='events'>
      {events.map((eventRecord, i) => (
        <EventListItem
          key={eventRecord.id}
          aria-label={`${eventRecord.event.type} event`}
          style={{ transform: `translateY(${i * 100}%)` }}
          selected={eventRecord.id === selectedEventRecordId}
          hasError={eventRecord.errors.length > 0}
          onClick={() => setSelectedEventRecordId(eventRecord.id)}>
          <EventIcon type={eventRecord.event.type} decoration={eventRecord.errors.length > 0 ? 'error' : null} />
          <EventSummary>
            <EventMeta>
              <EventTypeLabel aria-hidden>{eventRecord.event.type}</EventTypeLabel>
              <EventTime>
                <ScreenReaderOnly>Occurrence time</ScreenReaderOnly>
                <Timestamp>{eventRecord.phases.triggered.timestamp}</Timestamp>
              </EventTime>
            </EventMeta>
            <EventAttributes>
              <EventLabel event={eventRecord.event} />
              <EventDestinations destinations={eventRecord.phases.delivered?.destinations} />
            </EventAttributes>
            {'queryMatch' in eventRecord && <QueryMatchPreview>{eventRecord.queryMatch}</QueryMatchPreview>}
          </EventSummary>
        </EventListItem>
      ))}
    </EventListContainer>
  )
}
