import React from 'react'

import { ClockIcon, ErrorIcon, GreenlightIcon } from '~/resources/icons'
import { EventRecord } from '~/src/types/core'
import { EventTimeline } from '../EventTimeline'
import { Timestamp } from '../Timestamp'

import { useEventDeliveryStatus } from './hooks'
import {
  Attribute,
  AttributeName,
  AttributeValue,
  EventTypeHeading,
  QuickSummaryTable,
  SummaryTableBody
} from './style'


const dateTimeFmtOptions: Intl.DateTimeFormatOptions = {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  fractionalSecondDigits: 2
}

export const EventDetail = ({ eventRecord }: { eventRecord: EventRecord }) => {
  const [eventStatus, statusIcon] = useEventDeliveryStatus(eventRecord)

  return (
    <>
      <EventTypeHeading>{eventRecord.event.type} event</EventTypeHeading>
      <QuickSummaryTable>
        <SummaryTableBody>
          <Attribute icon={ClockIcon}>
            <AttributeName scope='row'>Occurrence time</AttributeName>
            <AttributeValue>
              <Timestamp options={dateTimeFmtOptions}>{eventRecord.phases.triggered.timestamp}</Timestamp>
            </AttributeValue>
          </Attribute>
          <Attribute icon={statusIcon}>
            <AttributeName scope='row'>Status</AttributeName>
            <AttributeValue>{eventStatus}</AttributeValue>
          </Attribute>
          <Attribute icon={eventRecord.errors.length > 0 ? ErrorIcon : GreenlightIcon}>
            <AttributeName scope='row'>Problems</AttributeName>
            <AttributeValue>
              {eventRecord.errors.length > 0
                ? `${eventRecord.errors.length} error${eventRecord.errors.length === 1 ? '' : 's'}`
                : 'All clear'}
            </AttributeValue>
          </Attribute>
        </SummaryTableBody>
      </QuickSummaryTable>
      <EventTimeline timeline={eventRecord.timeline} />
    </>
  )
}
