import React, { useState } from "react";
import { Occurrence } from "plucky_client/plucky";
import styles from "./occurrence_table.module.css";

import { DateTime } from "luxon";
import { ExpandButton } from "components/expand_button";
import { OccurrenceDetails } from "components/occurrence_details";

export interface OccurrenceRowProps {
  occurrence: Occurrence;
}

function formatTimestamp(d: DateTime): string {
  const dateStr = d.toISODate();
  const timeStr = d.toISOTime({
    suppressMilliseconds: true,
    includeOffset: false,
  });
  return `${dateStr} ${timeStr}`;
}

export function OccurrenceRow(props: OccurrenceRowProps) {
  const occurrence = props.occurrence;
  const msg = occurrence.message;
  const level = occurrence.level;

  const dateTime = DateTime.fromJSDate(occurrence.timestamp);
  const timestampLocal = formatTimestamp(dateTime);
  const timestampUTC = formatTimestamp(dateTime.toUTC());

  const [showDetails, updateShowDetails] = useState(false);

  let detailsRow = null;
  if (showDetails) {
    detailsRow = (
      <div className={styles.detailsRow}>
        <OccurrenceDetails occurrence={occurrence} />
      </div>
    );
  }
  return (
    <>
      <div className={styles.row}>{timestampLocal}</div>
      <div className={styles.row}>{timestampUTC}</div>
      <div className={styles.row}>{msg}</div>
      <div className={styles.row}>{occurrence.requestId}</div>
      <div className={styles.row}>{level}</div>
      <div className={styles.row}>
        <ExpandButton
          expanded={showDetails}
          onToggle={(expanded) => {
            updateShowDetails(expanded);
          }}
        />
      </div>
      <div className={styles.rowLine} />

      {detailsRow}
    </>
  );
}
