'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

interface LogEntry {
  id: string
  action: string
  entity: string
  entityId: string | null
  details: string | null
  createdAt: string
  user: { name: string; username: string }
}

const entityIcons: Record<string, string> = {
  LaunchTask: '📋',
  SubscriptionTier: '💰',
  ContentSession: '📅',
  FunnelMetric: '📊',
}

const actionColors: Record<string, string> = {
  created: 'text-green-400',
  updated: 'text-blue-400',
  recorded: 'text-purple-400',
}

export default function ActivityPage() {
  const [logs, setLogs] = useState<LogEntry[]>([])
  const [loading, setLoading] = useState(true)
  const router = useRouter()

  useEffect(() => {
    fetch('/api/activity')
      .then(res => { if (res.status === 401) { router.push('/login'); return null } return res.json() })
      .then(d => { if (d) setLogs(d.logs); setLoading(false) })
  }, [router])

  if (loading) return <div className="flex items-center justify-center h-full"><div className="text-brand-muted">Loading...</div></div>

  // Group by date
  const grouped = new Map<string, LogEntry[]>()
  logs.forEach(log => {
    const date = new Date(log.createdAt).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
    if (!grouped.has(date)) grouped.set(date, [])
    grouped.get(date)!.push(log)
  })

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-brand-text">Activity Log</h1>
        <p className="text-brand-muted text-sm mt-1">Auto-logged from dashboard actions</p>
      </div>

      <div className="space-y-8">
        {Array.from(grouped.entries()).map(([date, entries]) => (
          <div key={date}>
            <h3 className="text-xs font-semibold text-brand-muted uppercase tracking-wider mb-4">{date}</h3>
            <div className="space-y-1">
              {entries.map(log => (
                <div key={log.id} className="flex items-start gap-4 py-3 px-4 rounded-lg hover:bg-brand-card/50 transition-colors group">
                  <div className="text-lg shrink-0 mt-0.5">{entityIcons[log.entity] || '📝'}</div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-brand-text">
                      <span className="font-medium">{log.user.name}</span>{' '}
                      <span className={actionColors[log.action] || 'text-brand-muted'}>{log.action}</span>{' '}
                      <span className="text-brand-muted">{log.entity.replace(/([A-Z])/g, ' $1').trim()}</span>
                    </p>
                    {log.details && <p className="text-xs text-brand-muted mt-0.5 truncate">{log.details}</p>}
                  </div>
                  <span className="text-xs text-brand-muted shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                    {new Date(log.createdAt).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))}
        {logs.length === 0 && (
          <div className="bg-brand-card border border-brand-border rounded-xl p-12 text-center">
            <p className="text-brand-muted">No activity recorded yet. Actions taken in the dashboard will appear here.</p>
          </div>
        )}
      </div>
    </div>
  )
}
