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

const TYPE_COLORS = {
  COE: 'bg-blue-900/50 text-blue-300',
  P2P: 'bg-purple-900/50 text-purple-300',
  P3P: 'bg-orange-900/50 text-orange-300',
}

function fmtDuration(s) {
  if (s == null) return null
  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`
}

function TagPill({ label, value, colorClass }) {
  if (value == null || value === '') return null
  return (
    <div className="flex flex-col gap-0.5 min-w-[60px]">
      <span className="text-[10px] text-slate-500 uppercase tracking-wide leading-none">{label}</span>
      <span className={`text-xs font-medium px-2 py-0.5 rounded whitespace-nowrap ${colorClass ?? 'bg-slate-800 text-slate-300'}`}>
        {value}
      </span>
    </div>
  )
}

function SortTh({ colKey, label, sort, onSort }) {
  return (
    <th
      onClick={() => onSort(colKey)}
      className="px-3 py-3 cursor-pointer select-none whitespace-nowrap hover:text-slate-200 transition-colors"
    >
      {label}
      {sort.key === colKey && <span className="ml-1">{sort.dir === 1 ? '↑' : '↓'}</span>}
    </th>
  )
}

export default function TestTable({ tests = [], isLoading }) {
  const [sort, setSort] = useState({ key: 'filename', dir: 1 })
  const [expanded, setExpanded] = useState(new Set())

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

  function toggleExpand(id) {
    setExpanded(prev => {
      const next = new Set(prev)
      next.has(id) ? next.delete(id) : next.add(id)
      return next
    })
  }

  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="rounded-xl border border-slate-800 overflow-hidden">
      <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>
            <th className="px-3 py-3 w-6" />
            <SortTh colKey="filename" label="File" sort={sort} onSort={toggleSort} />
            <SortTh colKey="completed"  label="Status"    sort={sort} onSort={toggleSort} />
          </tr>
        </thead>
        <tbody>
          {sorted.map((test, i) => {
            const isOpen = expanded.has(test.id)
            const rowBase = 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'

            return (
              <React.Fragment key={test.id}>
                <tr
                  onClick={() => toggleExpand(test.id)}
                  className={`border-t border-slate-800 cursor-pointer transition-colors ${rowBase}`}
                >
                  <td className="px-3 py-2 text-slate-500 text-xs select-none">
                    {isOpen ? '▾' : '▸'}
                  </td>
                  <td className="px-3 py-2 text-xs text-slate-200 whitespace-nowrap">
                    {test.filename ?? '—'}
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap">
                    <StatusBadge completed={test.completed} />
                  </td>
                </tr>
                {isOpen && (
                  <tr className={`border-t border-slate-700/60 ${test.completed ? 'bg-emerald-950/10' : 'bg-slate-900/80'}`}>
                    <td colSpan={3} className="px-6 py-4">
                      <div className="flex flex-wrap gap-3">
                        <TagPill label="File ID"      value={test.test_id} />
                        <TagPill label="Type"         value={test.interference} colorClass={TYPE_COLORS[test.interference]} />
                        <TagPill label="Device"       value={test.device} />
                        <TagPill label="Rotation"     value={test.rotation} />
                        <TagPill label="Test Point"   value={test.test_point} />
                        <TagPill label="RSSI"         value={test.rssi} />
                        <TagPill label="Station"      value={test.station} />
                        <TagPill label="Band"         value={test.band} />
                        <TagPill label="Channel"      value={test.channel} />
                        <TagPill label="Bandwidth"    value={test.bandwidth} />
                        <TagPill label="Direction"    value={test.direction} />
                        <TagPill label="Elapsed Time" value={fmtDuration(test.duration_seconds)} />
                      </div>
                      {(() => {
                        const rows = test.tput_results ? JSON.parse(test.tput_results) : []
                        if (!test.completed || rows.length === 0) return null
                        return (
                          <div className="mt-3 pt-3 border-t border-slate-700/50">
                            <table className="text-xs w-auto border-collapse">
                              <thead>
                                <tr className="text-slate-500 uppercase tracking-wide">
                                  <th className="pr-6 pb-1 text-left font-medium">Station</th>
                                  <th className="pr-6 pb-1 text-right font-medium">Throughput</th>
                                  <th className="pr-6 pb-1 text-right font-medium">DL RSSI</th>
                                  <th className="pb-1 text-right font-medium">UL RSSI</th>
                                </tr>
                              </thead>
                              <tbody>
                                {rows.map(r => (
                                  <tr key={r.station} className="text-slate-300">
                                    <td className="pr-6 py-0.5 text-cyan-400 font-medium">STA{r.station}</td>
                                    <td className="pr-6 py-0.5 text-right">{r.tput} Mbps</td>
                                    <td className="pr-6 py-0.5 text-right">{r.dlRssi} dBm</td>
                                    <td className="py-0.5 text-right">{r.ulRssi} dBm</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        )
                      })()}
                    </td>
                  </tr>
                )}
              </React.Fragment>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}
