import React, { useEffect, useState } from 'react'

import { EventError, EventRecord } from '../..'
import { JSONView } from '../JSONView'

import {
  ErrorDescription,
  ErrorHeading,
  ErrorMessage,
  JSONViewContainer,
  SnapshotIcon,
  SnapshotItem,
  SnapshotList,
  SnapshotPreview,
  TimelineContainer
} from './style'


export type EventTimelineProps = {
  timeline: EventRecord['timeline']
}

export const EventTimeline = ({ timeline }: EventTimelineProps) => {
  const [selectedSnapshotIndex, setSelectedSnapshotIndex] = useState<number>()

  const activeSnapshot = timeline.at(selectedSnapshotIndex || 0)

  useEffect(() => setSelectedSnapshotIndex(undefined), [activeSnapshot.id])

  return (
    <TimelineContainer>
      <SnapshotList>
        {timeline.map((snapshot, i) => (
          <SnapshotItem
            key={i}
            item={snapshot}
            selected={snapshot === activeSnapshot}
            onClick={() => setSelectedSnapshotIndex(i)}>
            <SnapshotIcon />
          </SnapshotItem>
        ))}
      </SnapshotList>
      <SnapshotPreview>
        {'type' in activeSnapshot && (activeSnapshot as EventError).type === 'error' && (
          <ErrorMessage>
            <ErrorHeading>{(activeSnapshot as EventError).message}</ErrorHeading>
            {activeSnapshot.description && (
              <ErrorDescription>{(activeSnapshot as EventError).description}</ErrorDescription>
            )}
          </ErrorMessage>
        )}
        <JSONViewContainer>
          <JSONView value={activeSnapshot.event} />
        </JSONViewContainer>
      </SnapshotPreview>
    </TimelineContainer>
  )
}
