'use client'

import { useState, useMemo, useCallback } from 'react'
import type { GuardrailData } from '@/lib/types'
import { fmtPct, guardrailCreatorColor } from '@/lib/utils'
import { LabLogo } from '@/components/LabLogo'

type SortKey = 'rank' | 'recall' | 'precision' | 'f1'

interface Props {
  guardrails: GuardrailData[]
}

function scoreColor(v: number | null): string {
  if (v === null) return 'var(--text-3)'
  if (v >= 0.9) return '#22C55E'
  if (v >= 0.75) return '#4ADE80'
  if (v >= 0.6) return '#F0A030'
  return '#F4333D'
}

function ScoreCell({
  value,
  color,
  format,
}: {
  value: number | null
  color: string
  format: (v: number | null) => string
}) {
  const barWidth = value === null ? 0 : value

  return (
    <td className="score-cell">
      {value === null ? (
        <span className="score-null">-</span>
      ) : (
        <>
          <div className="score-val" style={{ color }}>{format(value)}</div>
          <div className="score-bar-track">
            <div
              className="score-bar-fill"
              style={{ width: `${barWidth * 100}%`, background: color }}
            />
          </div>
        </>
      )}
    </td>
  )
}

function ExpandedRow({ guardrail }: { guardrail: GuardrailData }) {
  return (
    <tr className="lb-expand-row">
      <td colSpan={7}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '2rem', padding: '0.75rem 1.5rem' }}>
          <span style={{ fontSize: 12, color: 'var(--text-3)' }}>
            Detections: <span style={{ fontWeight: 700, color: 'var(--text-1)', fontFamily: 'inherit', fontVariantNumeric: 'tabular-nums' }}>{guardrail.detections}</span>
          </span>
          <span style={{ fontSize: 12, color: 'var(--text-3)' }}>
            Last Run: <span style={{ color: 'var(--text-2)' }}>{guardrail.lastRun}</span>
          </span>
        </div>
      </td>
    </tr>
  )
}

export default function GuardrailsTable({ guardrails }: Props) {
  const [sortKey, setSortKey] = useState<SortKey>('recall')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
  const [query, setQuery] = useState('')
  const [expandedRank, setExpandedRank] = useState<number | null>(null)
  const [activeCreator, setActiveCreator] = useState<string | null>(null)

  const creators = useMemo(() => [...new Set(guardrails.map(g => g.creator))].sort(), [guardrails])

  const handleSort = useCallback((key: SortKey) => {
    if (sortKey === key) {
      setSortDir(d => (d === 'asc' ? 'desc' : 'asc'))
    } else {
      setSortKey(key)
      setSortDir('desc')
    }
  }, [sortKey])

  const sorted = useMemo(() => {
    let list = [...guardrails]

    if (activeCreator) list = list.filter(g => g.creator === activeCreator)
    if (query.trim()) {
      const q = query.toLowerCase()
      list = list.filter(
        g => g.guardrail.toLowerCase().includes(q) || g.creator.toLowerCase().includes(q),
      )
    }

    list.sort((a, b) => {
      let va: number | null, vb: number | null
      if (sortKey === 'rank') { va = a.rank; vb = b.rank }
      else if (sortKey === 'recall') { va = a.recall; vb = b.recall }
      else if (sortKey === 'precision') { va = a.precision; vb = b.precision }
      else { va = a.f1; vb = b.f1 }

      if (va === null && vb === null) return 0
      if (va === null) return 1
      if (vb === null) return -1
      return sortDir === 'asc' ? va - vb : vb - va
    })

    return list
  }, [guardrails, activeCreator, query, sortKey, sortDir])

  function SortArrow({ k }: { k: SortKey }) {
    if (sortKey !== k) return <span style={{ color: 'var(--border-2)', marginLeft: 4 }}>↕</span>
    return <span style={{ color: 'var(--accent)', marginLeft: 4 }}>{sortDir === 'asc' ? '↑' : '↓'}</span>
  }

  return (
    <div>
      {/* Controls */}
      <div className="lb-controls">
        <div className="lb-search-wrap">
          <svg className="lb-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" />
          </svg>
          <input
            className="lb-search"
            placeholder="Search guardrails..."
            value={query}
            onChange={e => setQuery(e.target.value)}
          />
        </div>

        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {creators.map(c => {
            const cc = guardrailCreatorColor(c)
            return (
              <button
                key={c}
                className={`filter-chip ${activeCreator === c ? 'active' : ''}`}
                style={activeCreator === c ? {
                  borderColor: cc,
                  color: cc,
                  background: `${cc}12`,
                } : {}}
                onClick={() => setActiveCreator(prev => prev === c ? null : c)}
              >
                <span className="filter-chip-logo"><LabLogo creator={c} /></span>
                {c}
              </button>
            )
          })}
        </div>
      </div>

      {/* Table */}
      <div className="lb-table-wrap">
        <table className="lb-table">
          <thead>
            <tr>
              <th onClick={() => handleSort('rank')} className={sortKey === 'rank' ? 'sort-active' : ''} style={{ width: 48 }}>
                # <SortArrow k="rank" />
              </th>
              <th style={{ width: 130 }}>Creator</th>
              <th>Guardrail</th>
              <th onClick={() => handleSort('recall')} className={sortKey === 'recall' ? 'sort-active' : ''}>
                Recall <SortArrow k="recall" />
              </th>
              <th onClick={() => handleSort('precision')} className={sortKey === 'precision' ? 'sort-active' : ''}>
                Precision <SortArrow k="precision" />
              </th>
              <th onClick={() => handleSort('f1')} className={sortKey === 'f1' ? 'sort-active' : ''}>
                F1 <SortArrow k="f1" />
              </th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((g, i) => {
              const isExpanded = expandedRank === g.rank
              const cc = guardrailCreatorColor(g.creator)

              return [
                <tr
                  key={`row-${g.rank}`}
                  className={isExpanded ? 'row-expanded' : ''}
                  style={{ background: `${cc}08` }}
                >
                  <td>
                    <span className={`rank-cell ${i < 3 && !activeCreator && !query ? 'rank-top3' : ''}`}>
                      {g.rank}
                    </span>
                  </td>
                  <td>
                    <button
                      className="creator-badge"
                      style={{ background: `${cc}18`, color: cc }}
                      onClick={() => setActiveCreator(prev => prev === g.creator ? null : g.creator)}
                    >
                      <span className="creator-badge-logo">
                        <LabLogo creator={g.creator} />
                      </span>
                      {g.creator}
                    </button>
                  </td>
                  <td>
                    <button
                      className="model-name"
                      onClick={() => setExpandedRank(isExpanded ? null : g.rank)}
                    >
                      <svg
                        className={`expand-chevron ${isExpanded ? 'open' : ''}`}
                        width="12"
                        height="12"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2.5"
                      >
                        <polyline points="9 18 15 12 9 6" />
                      </svg>
                      {g.guardrail}
                    </button>
                  </td>
                  <ScoreCell
                    value={g.recall}
                    color={scoreColor(g.recall)}
                    format={v => fmtPct(v)}
                  />
                  <ScoreCell
                    value={g.precision}
                    color={scoreColor(g.precision)}
                    format={v => fmtPct(v)}
                  />
                  <ScoreCell
                    value={g.f1}
                    color={scoreColor(g.f1)}
                    format={v => fmtPct(v)}
                  />
                </tr>,

                isExpanded && (
                  <ExpandedRow key={`expand-${g.rank}`} guardrail={g} />
                ),
              ]
            })}
          </tbody>
        </table>
      </div>

      <div style={{ marginTop: 12 }}>
        <span style={{ fontSize: 12, color: 'var(--text-3)' }}>
          {sorted.length} of {guardrails.length} guardrails
        </span>
      </div>
    </div>
  )
}
