'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { ChevronLeft, History, ListTodo, Target, Lightbulb, Mic, Sparkles, Loader2 } from 'lucide-react'

interface Entry { id: string; type: string; summary: string; createdAt: string }

// Icon by type prefix (reminder.* / focus.* / thought.* / capture.* / organize.*).
function iconFor(type: string) {
  if (type.startsWith('reminder.')) return ListTodo
  if (type.startsWith('focus.')) return Target
  if (type.startsWith('thought.')) return Lightbulb
  if (type.startsWith('capture.')) return Mic
  if (type.startsWith('organize.')) return Sparkles
  return History
}

function dayLabel(iso: string): string {
  const d = new Date(iso)
  const today = new Date(); today.setHours(0, 0, 0, 0)
  const that = new Date(d); that.setHours(0, 0, 0, 0)
  const diff = Math.round((today.getTime() - that.getTime()) / 86400000)
  if (diff === 0) return 'Today'
  if (diff === 1) return 'Yesterday'
  return d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })
}

export function ActivityList() {
  const [entries, setEntries] = useState<Entry[]>([])
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    fetch('/api/activity', { cache: 'no-store' })
      .then(r => (r.ok ? r.json() : { entries: [] }))
      .then(d => setEntries(d.entries || []))
      .finally(() => setLoaded(true))
  }, [])

  // Group consecutive entries by day.
  const groups: { label: string; items: Entry[] }[] = []
  for (const e of entries) {
    const label = dayLabel(e.createdAt)
    const last = groups[groups.length - 1]
    if (last && last.label === label) last.items.push(e)
    else groups.push({ label, items: [e] })
  }

  return (
    <div className="min-h-screen max-w-md mx-auto flex flex-col">
      <header className="safe-top px-4 pb-3 flex items-center gap-2">
        <Link href="/" className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
          <ChevronLeft className="h-4 w-4" /> Dashboard
        </Link>
        <span className="ml-auto font-semibold inline-flex items-center gap-1.5"><History className="h-4 w-4 text-primary" /> Activity</span>
      </header>

      <main className="flex-1 px-4 pb-10 space-y-4">
        {!loaded && <div className="py-10 text-center"><Loader2 className="h-5 w-5 animate-spin mx-auto text-muted-foreground" /></div>}
        {loaded && entries.length === 0 && <p className="text-sm text-muted-foreground text-center py-10">No activity yet — it starts recording from today.</p>}

        {groups.map(g => (
          <section key={g.label} className="space-y-1.5">
            <div className="px-1 text-sm font-semibold">{g.label}</div>
            <ul className="space-y-1.5">
              {g.items.map(e => {
                const Icon = iconFor(e.type)
                return (
                  <li key={e.id} className="flex items-start gap-2.5 rounded-xl border border-border bg-card px-3 py-2">
                    <Icon className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" />
                    <span className="text-sm min-w-0 flex-1">{e.summary}</span>
                    <span className="text-xs text-muted-foreground shrink-0 tabular-nums">
                      {new Date(e.createdAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}
                    </span>
                  </li>
                )
              })}
            </ul>
          </section>
        ))}
      </main>
    </div>
  )
}
