'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { Loader2, Clock, CheckCircle2, AlertCircle, Mic, FileText, ListTodo, CalendarClock, Lightbulb, ChevronRight, ChevronDown } from 'lucide-react'

interface Capture {
  id: string
  status: 'PENDING' | 'PROCESSING' | 'DONE' | 'FAILED'
  textNote: string | null
  transcript: string | null
  hasAudio: boolean
  imageIds: string[]
  counts: { reminders: number; events: number; thoughts: number }
  error: string | null
  createdAt: string
}

function relativeTime(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const s = Math.floor(diff / 1000)
  if (s < 60) return 'just now'
  const m = Math.floor(s / 60)
  if (m < 60) return `${m}m ago`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h}h ago`
  return `${Math.floor(h / 24)}d ago`
}

const STATUS: Record<Capture['status'], { label: string; icon: typeof Clock; cls: string }> = {
  PENDING: { label: 'Queued', icon: Clock, cls: 'text-muted-foreground' },
  PROCESSING: { label: 'Processing', icon: Loader2, cls: 'text-primary' },
  DONE: { label: 'Done', icon: CheckCircle2, cls: 'text-emerald-600' },
  FAILED: { label: 'Failed', icon: AlertCircle, cls: 'text-destructive' },
}

// Dashboard shows a short list by default; "Show all" expands to the full
// fetched window (the API caps at 30).
const COLLAPSED_COUNT = 8

export function CaptureList() {
  const [captures, setCaptures] = useState<Capture[]>([])
  const [loaded, setLoaded] = useState(false)
  const [expanded, setExpanded] = useState(false)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const load = useCallback(async () => {
    try {
      const res = await fetch('/api/captures', { cache: 'no-store' })
      if (!res.ok) return
      const data = await res.json()
      setCaptures(data.captures || [])
    } finally {
      setLoaded(true)
    }
  }, [])

  useEffect(() => {
    load()
    const onUploaded = () => load()
    window.addEventListener('capture-uploaded', onUploaded)
    timerRef.current = setInterval(load, 4000)
    return () => {
      window.removeEventListener('capture-uploaded', onUploaded)
      if (timerRef.current) clearInterval(timerRef.current)
    }
  }, [load])

  if (loaded && captures.length === 0) {
    return <p className="text-sm text-muted-foreground text-center py-6">No captures yet — record or jot something above.</p>
  }

  const visible = expanded ? captures : captures.slice(0, COLLAPSED_COUNT)

  return (
    <ul className="space-y-2">
      {visible.map(c => {
        const st = STATUS[c.status]
        const Icon = st.icon
        const body = c.transcript || c.textNote
        const total = c.counts.reminders + c.counts.events + c.counts.thoughts
        return (
          <li key={c.id}>
            <Link href={`/capture/${c.id}`} className="block rounded-xl border border-border bg-card p-3 hover:border-primary/40 transition-colors">
              <div className="flex items-center justify-between gap-2 mb-1">
                <span className={`inline-flex items-center gap-1.5 text-xs font-medium ${st.cls}`}>
                  <Icon className={`h-3.5 w-3.5 ${c.status === 'PROCESSING' ? 'animate-spin' : ''}`} />
                  {st.label}
                </span>
                <span className="text-xs text-muted-foreground inline-flex items-center gap-1">
                  {relativeTime(c.createdAt)}
                  <ChevronRight className="h-3.5 w-3.5" />
                </span>
              </div>

              <div className="flex gap-2">
                {c.imageIds.length > 0 && (
                  <div className="flex -space-x-2 shrink-0">
                    {c.imageIds.slice(0, 3).map(id => (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img key={id} src={`/api/image/${id}?thumb=1`} alt="" className="w-10 h-10 rounded-md object-cover border border-card" />
                    ))}
                  </div>
                )}
                <div className="min-w-0 flex-1">
                  {body ? (
                    <p className="text-sm line-clamp-3">{body}</p>
                  ) : (
                    <p className="text-sm text-muted-foreground inline-flex items-center gap-1.5">
                      {c.hasAudio ? <><Mic className="h-3.5 w-3.5" /> voice note</> : <><FileText className="h-3.5 w-3.5" /> capture</>}
                      {c.status !== 'DONE' && c.status !== 'FAILED' && ' — transcribing…'}
                    </p>
                  )}
                  {c.status === 'FAILED' && c.error && (
                    <p className="text-xs text-destructive mt-1">{c.error}</p>
                  )}
                  {total > 0 && (
                    <div className="flex items-center gap-3 mt-1.5 text-xs text-muted-foreground">
                      {c.counts.reminders > 0 && <span className="inline-flex items-center gap-1"><ListTodo className="h-3 w-3" />{c.counts.reminders}</span>}
                      {c.counts.events > 0 && <span className="inline-flex items-center gap-1"><CalendarClock className="h-3 w-3" />{c.counts.events}</span>}
                      {c.counts.thoughts > 0 && <span className="inline-flex items-center gap-1"><Lightbulb className="h-3 w-3" />{c.counts.thoughts}</span>}
                    </div>
                  )}
                </div>
              </div>
            </Link>
          </li>
        )
      })}
      {!expanded && captures.length > COLLAPSED_COUNT && (
        <li>
          <button onClick={() => setExpanded(true)}
            className="w-full inline-flex items-center justify-center gap-1.5 text-sm text-muted-foreground rounded-xl border border-border py-2 hover:bg-muted">
            <ChevronDown className="h-4 w-4" /> Show all ({captures.length})
          </button>
        </li>
      )}
    </ul>
  )
}
