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

import { selectEventList } from '~/src/store/selectors/selectEventList'
import { selectEventMap } from '~/src/store/selectors/selectEventMap'
import { selectUIState } from '~/src/store/selectors/selectUIState'
import { EventDetail } from '../EventDetail'
import { EventList } from '../EventList'
import { EventListFilter } from '../EventListFilter'
import { selectFilteredEventList } from '~/src/store/selectors/selectFilteredEventList'
import { selectEventsFilter } from '~/src/store/selectors/selectEventsFilter'
import { Dispatch } from '~/src/store'

import { DetailPane, EventExplorerContainer, ListPane, NoMatchingEventsMsg, PlaceholderMsg } from './style'


export const EventExplorer = () => {
  const { selectedEventRecordId } = useSelector(selectUIState)
  const eventList = useSelector(selectEventList)
  const eventMap = useSelector(selectEventMap)
  const eventsFilter = useSelector(selectEventsFilter)
  const filteredEventList = useSelector(selectFilteredEventList)
  const {
    ui: { setEventsFilter }
  } = useDispatch<Dispatch>()

  if (eventList.length === 0) {
    return <PlaceholderMsg>Waiting for events...</PlaceholderMsg>
  }

  return (
    <EventExplorerContainer>
      <ListPane>
        <EventListFilter filters={eventsFilter} onFiltersChange={setEventsFilter} />
        {filteredEventList.length === 0 ? (
          <NoMatchingEventsMsg>No events match your filters</NoMatchingEventsMsg>
        ) : (
          <EventList events={filteredEventList} selectedEventRecordId={selectedEventRecordId} />
        )}
      </ListPane>
      <DetailPane>
        {eventMap[selectedEventRecordId] ? (
          <EventDetail eventRecord={eventMap[selectedEventRecordId]} />
        ) : (
          <PlaceholderMsg>Select an event to view its anatomy</PlaceholderMsg>
        )}
      </DetailPane>
    </EventExplorerContainer>
  )
}
