import {useEffect, useRef} from 'react'
import type {LogEntry} from '../types'
import {formatBytes} from '../util'

type Props = {
  log: LogEntry[]
  onClear: () => void
}

const time = (t: number) =>
  new Date(t).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'})

export function MessageLog({log, onClear}: Props) {
  const bottomRef = useRef<HTMLDivElement>(null)

  // autoscroll to the newest entry
  useEffect(() => {
    bottomRef.current?.scrollIntoView({behavior: 'smooth', block: 'end'})
  }, [log.length])

  return (
    <div className="panel log-panel">
      <h2 className="panel-title">
        Message log
        <button className="btn tiny" onClick={onClear} disabled={log.length === 0}>
          clear
        </button>
      </h2>

      <div className="log">
        {log.length === 0 && (
          <p className="empty">Messages and transfers will appear here.</p>
        )}
        {log.map(e => (
          <LogRow key={e.key} e={e} />
        ))}
        <div ref={bottomRef} />
      </div>
    </div>
  )
}

function LogRow({e}: {e: LogEntry}) {
  if (e.kind === 'system') {
    return (
      <div className="log-row system">
        <span className="log-time">{time(e.time)}</span>
        <span className="log-body">{e.text}</span>
      </div>
    )
  }

  const arrow = e.dir === 'out' ? '→' : '←'
  const who =
    e.dir === 'out' ? `to ${e.peerName}` : `from ${e.peerName}`

  return (
    <div className={`log-row ${e.dir}`}>
      <span className="log-time">{time(e.time)}</span>
      <span className="log-body">
        <span className="log-who">
          {arrow} {who}
        </span>
        {e.kind === 'text' ? (
          <span className="log-text">{e.text}</span>
        ) : (
          <span className="log-binary">
            📦 <b>{e.fileName}</b> · {formatBytes(e.size ?? 0)}
            {e.blobUrl && (
              <a className="dl" href={e.blobUrl} download={e.fileName}>
                download
              </a>
            )}
            {e.sha256 && (
              <code className="sha" title={`SHA-256: ${e.sha256}`}>
                sha256 {e.sha256.slice(0, 12)}…
              </code>
            )}
          </span>
        )}
      </span>
    </div>
  )
}
