import { useState } from 'react'
import StatusBadge from './StatusBadge'

const COLS = [
  { key: 'file_id',      label: 'File ID' },
  { key: 'interference', label: 'Type' },
  { key: 'device',       label: 'Device' },
  { key: 'rotation',     label: 'Rotation' },
  { key: 'test_point',   label: 'Test Point' },
  { key: 'rssi',         label: 'RSSI' },
  { key: 'station',      label: 'Station' },
  { key: 'band',         label: 'Band' },
  { key: 'channel',      label: 'Channel' },
  { key: 'bandwidth',    label: 'BW' },
  { key: 'direction',    label: 'Dir' },
  { key: 'completed',    label: 'Status' },
  { key: 'duration_seconds', label: 'Duration' },
]

function fmtDuration(s) {
  if (s == null) return '—'
  const h = Math.floor(s / 3600)
  const m = Math.floor((s % 3600) / 60)
  const sec = Math.floor(s % 60)
  if (h > 0) return `${h}h ${m}m`
  if (m > 0) return `${m}m ${sec}s`
  return `${sec}s`
}

export default function TestTable({ tests = [], isLoading }) {
  const [sort, setSort] = useState({ key: 'file_id', dir: 1 })

  function toggleSort(key) {
    setSort(s => ({ key, dir: s.key === key ? -s.dir : 1 }))
  }

  const sorted = [...tests].sort((a, b) => {
    let av = a[sort.key] ?? ''
    let bv = b[sort.key] ?? ''
    if (typeof av === 'number' || typeof bv === 'number') return (av - bv) * sort.dir
    return String(av).localeCompare(String(bv)) * sort.dir
  })

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-16 text-slate-500">
        Loading tests…
      </div>
    )
  }

  if (tests.length === 0) {
    return (
      <div className="flex items-center justify-center py-16 text-slate-500">
        No tests match the current filters.
      </div>
    )
  }

  return (
    <div className="overflow-x-auto rounded-xl border border-slate-800">
      <table className="w-full text-sm text-left text-slate-300 border-collapse">
        <thead className="bg-slate-800 text-slate-400 text-xs uppercase tracking-wider">
          <tr>
            {COLS.map(col => (
              <th
                key={col.key}
                onClick={() => toggleSort(col.key)}
                className="px-3 py-3 cursor-pointer select-none whitespace-nowrap hover:text-slate-200 transition-colors"
              >
                {col.label}
                {sort.key === col.key && (
                  <span className="ml-1">{sort.dir === 1 ? '↑' : '↓'}</span>
                )}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {sorted.map((test, i) => (
            <tr
              key={test.id}
              className={`border-t border-slate-800 transition-colors ${
                test.completed
                  ? 'bg-emerald-950/20 hover:bg-emerald-950/40'
                  : i % 2 === 0 ? 'bg-slate-900 hover:bg-slate-800' : 'bg-slate-900/60 hover:bg-slate-800'
              }`}
            >
              <td className="px-3 py-2 font-mono text-xs text-slate-200 whitespace-nowrap">{test.file_id ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">
                <span className={`text-xs font-semibold px-1.5 py-0.5 rounded ${
                  test.interference === 'COE' ? 'bg-blue-900/50 text-blue-300' :
                  test.interference === 'P2P' ? 'bg-purple-900/50 text-purple-300' :
                  test.interference === 'P3P' ? 'bg-orange-900/50 text-orange-300' : ''
                }`}>
                  {test.interference ?? '—'}
                </span>
              </td>
              <td className="px-3 py-2 whitespace-nowrap">{test.device    ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.rotation  ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.test_point ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.rssi       ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.station    ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.band       ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.channel    ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.bandwidth  ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap">{test.direction  ?? '—'}</td>
              <td className="px-3 py-2 whitespace-nowrap"><StatusBadge completed={test.completed} /></td>
              <td className="px-3 py-2 whitespace-nowrap text-slate-400">{fmtDuration(test.duration_seconds)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
