import React from "react";
import { StackTrace } from "plucky_client/plucky";
import styles from "./styles.module.css";
import classNames from "classnames/bind";
import { linkColor } from "theme";
import { Link } from "@chakra-ui/react";

export interface StackFrameProps {
  stackFrame: StackTrace;
}

export function StackFrame(props: StackFrameProps) {
  const stackFrame = props.stackFrame;
  if (!stackFrame) {
    return null;
  }

  let pkgLink = null;
  const pkg = stackFrame.brazilPkgName;
  if (pkg) {
    pkgLink = (
      <Link href={stackFrame.pkgUrl} color={linkColor}>
        {pkg}
      </Link>
    );
  }

  let fileSpan = null;
  const file = stackFrame.shortFilePath;
  if (file) {
    fileSpan = <span className={styles.stackFrameValue}>{file} </span>;
  }

  let lineSpan = null;
  const line = stackFrame.line;
  if (line) {
    lineSpan = (
      <span>
        <span className={styles.stackFrameName}>line </span>
        <span className={styles.stackFrameValue}>{line} </span>
      </span>
    );
  }

  let methodSpan = null;
  const method = stackFrame.method;
  if (method) {
    methodSpan = (
      <span>
        <span className={styles.stackFrameName}>in </span>
        <span className={styles.stackFrameValue}>{method} </span>
      </span>
    );
  }

  let frame;
  if (stackFrame.lineUrl) {
    frame = (
      <Link href={stackFrame.lineUrl} color={linkColor}>
        {fileSpan} {lineSpan} {methodSpan}
      </Link>
    );
  } else {
    frame = (
      <>
        {fileSpan} {lineSpan} {methodSpan}
      </>
    );
  }
  return (
    <>
      <div
        className={classNames({
          [styles.relevantFrame]: stackFrame.relevant,
        })}
      >
        {pkgLink}
      </div>
      <div
        className={classNames({
          [styles.relevantFrame]: stackFrame.relevant,
        })}
      >
        {frame}
      </div>
    </>
  );
}
