import React from 'react'
import { JSONTree } from 'react-json-tree'

import { EventRecord } from '~/src/types/core'
import { EventIcon } from '../EventIcon'
import { Timestamp } from '../Timestamp'

import { AttrKey, AttrValue, EventDetailHeader, EventTypeBadge, JSONTreeContainer } from './style'


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

const theme = {
  scheme: 'monokai',
  author: 'wimer hazenberg (http://www.monokai.nl)',
  base00: '#fafafa',
  base01: '#383830',
  base02: '#49483e',
  base03: '#75715e',
  base04: '#a59f85',
  base05: '#f8f8f2',
  base06: '#f5f4f1',
  base07: '#f9f8f5',
  base08: '#f92672',
  base09: '#fd971f',
  base0A: '#f4bf75',
  base0B: '#a6e22e',
  base0C: '#a1efe4',
  base0D: '#66d9ef',
  base0E: '#ae81ff',
  base0F: '#cc6633'
}

const TreeView = ({ data }: { data: unknown }) => (
  <JSONTreeContainer>
    <JSONTree hideRoot theme={theme} data={data} />
  </JSONTreeContainer>
)

export const EventDetail = ({ eventRecord }: { eventRecord: EventRecord }) => {
  return (
    <>
      <EventDetailHeader>
        <EventTypeBadge>
          <EventIcon type={eventRecord.event.type} />
          {eventRecord.event.type}
        </EventTypeBadge>
      </EventDetailHeader>
      <AttrKey>Occurrence time</AttrKey>
      <AttrValue>
        <Timestamp options={dateTimeFmtOptions}>{eventRecord.phases.triggered.timestamp}</Timestamp>
      </AttrValue>
      <AttrKey>Event ID</AttrKey>
      <AttrValue>{eventRecord.event.messageId}</AttrValue>
      {eventRecord.event.type === 'track' && (
        <>
          <AttrKey>Event</AttrKey>
          <AttrValue>{eventRecord.event.event}</AttrValue>
          <AttrKey>Event properties</AttrKey>
          {Object.keys(eventRecord.event.properties).length > 0 ? (
            <TreeView data={eventRecord.event.properties} />
          ) : (
            <AttrValue>No properties were set</AttrValue>
          )}
        </>
      )}
    </>
  )
}
