'use client'
import { useState, useEffect, useCallback } from 'react'
import AILogCard from './AILogCard'
import { fetchAILog, clearAILog } from '@/lib/api/ai'
import { cn } from '@/lib/utils'

type Filter = 'ALL' | 'FILTER' | 'ADAPT' | 'ERRORS'

const LABELS: Record<Filter, string> = {
  ALL: 'All', FILTER: 'Filter calls', ADAPT: 'Adapt calls', ERRORS: 'Errors',
}

export default function AILogFeed() {
  const [entries,  setEntries]  = useState<any[]>([])
  const [debugOn,  setDebugOn]  = useState<boolean | null>(null)
  const [total,    setTotal]    = useState(0)
  const [filter,   setFilter]   = useState<Filter>('ALL')
  const [search,   setSearch]   = useState('')

  const load = useCallback(async () => {
    try {
      const data = await fetchAILog(200)
      setEntries(Array.isArray(data.entries) ? data.entries : [])
      setDebugOn(data.debug_enabled ?? null)
      setTotal(data.total_in_buffer ?? 0)
    } catch {}
  }, [])

  useEffect(() => {
    load()
    const t = setInterval(load, 5000)
    return () => clearInterval(t)
  }, [load])

  const filtered = entries.filter((e) => {
    if (filter === 'FILTER' && e.call_type !== 'filter') return false
    if (filter === 'ADAPT'  && e.call_type !== 'adapt')  return false
    if (filter === 'ERRORS' && e.direction !== 'error')  return false
    if (search && !JSON.stringify(e).toLowerCase().includes(search.toLowerCase())) return false
    return true
  })

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex gap-2 flex-wrap items-center">
        {(['ALL', 'FILTER', 'ADAPT', 'ERRORS'] as Filter[]).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={cn(
              'g-btn text-xs h-8',
              filter === f && '!border-g-green/40 !text-g-green !bg-g-green/8'
            )}
          >
            {LABELS[f]}
          </button>
        ))}
        <div className="relative ml-auto">
          <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-g-faint text-xs">⌕</span>
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search log…"
            className="g-input h-8 pl-7 text-xs w-44"
          />
        </div>
        <button onClick={load}  className="g-btn text-xs h-8">Refresh</button>
        <button
          onClick={async () => { await clearAILog(); setEntries([]); setTotal(0) }}
          className="g-btn-danger text-xs h-8"
        >
          Clear
        </button>
      </div>

      {/* Status strip */}
      <div className="flex items-center gap-4 text-xs text-g-faint">
        {debugOn === false && (
          <span className="flex items-center gap-1.5 text-g-amber">
            <span className="w-1.5 h-1.5 rounded-full bg-g-amber flex-shrink-0" />
            AI Debug is off — enable it in Settings → AI Filter to capture logs
          </span>
        )}
        {debugOn === true && (
          <span className="flex items-center gap-1.5 text-g-green">
            <span className="w-1.5 h-1.5 rounded-full bg-g-green animate-pulse flex-shrink-0" />
            AI Debug on
          </span>
        )}
        {total > 0 && <span>{total} entries · showing {filtered.length}</span>}
      </div>

      {/* Entries */}
      <div className="g-card overflow-hidden">
        <div className="max-h-[72vh] overflow-y-auto p-4 space-y-2">
          {filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-14 text-g-faint gap-2">
              <span className="text-3xl opacity-20">◎</span>
              <p className="text-sm">
                {debugOn === false
                  ? 'Enable AI Debug in Settings to start capturing logs'
                  : 'No AI log entries'}
              </p>
            </div>
          ) : (
            [...filtered].reverse().map((e) => <AILogCard key={e.id} entry={e} />)
          )}
        </div>
      </div>
    </div>
  )
}
