import React from 'react'
import { createRoot } from 'react-dom/client'
import browser from 'webextension-polyfill'
import { getHistory, setHistory, type DownloadHistoryItem } from '../lib/history'
import './styles.css'

function formatBytes(size: number): string {
  if (!Number.isFinite(size) || size <= 0) return '-'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let value = size
  let idx = 0
  while (value >= 1024 && idx < units.length - 1) {
    value /= 1024
    idx += 1
  }
  return `${value.toFixed(value >= 10 || idx === 0 ? 0 : 1)} ${units[idx]}`
}

function HistoryPage(): JSX.Element {
  const [history, setHistoryState] = React.useState<DownloadHistoryItem[]>([])

  React.useEffect(() => {
    const load = async () => setHistoryState(await getHistory())
    const id = window.setInterval(() => void load(), 1000)
    void load()
    return () => window.clearInterval(id)
  }, [])

  const clearAll = async () => {
    await setHistory([])
    setHistoryState([])
  }

  return (
    <div className="wrap">
      <h1>Download History</h1>
      <div className="actions">
        <button onClick={clearAll}>Clear</button>
      </div>
      <div className="list">
        {history.map((item) => {
          const progress = item.size > 0 ? Math.min(100, (item.downloaded * 100) / item.size) : 0
          return (
            <article key={item.gid} className="item">
              <div className="head">
                <div className="name">{item.name || item.gid}</div>
                <div className="meta">{item.status.toUpperCase()}</div>
              </div>
              <div className="bar"><span style={{ width: `${progress}%` }} /></div>
              <div className="meta">
                {formatBytes(item.downloaded)} / {formatBytes(item.size)}
              </div>
              <div className="actions">
                <button onClick={() => browser.tabs.create({ url: 'gdown://focus' }).catch(() => null)}>Open App</button>
              </div>
            </article>
          )
        })}
      </div>
    </div>
  )
}

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <HistoryPage />
  </React.StrictMode>
)
