import React, { useEffect, useState } from 'react'

function actorLabel(item) {
  if (!item.actor) {
    return 'System'
  }

  return item.actor.username ? `@${item.actor.username}` : item.actor.name || 'User'
}

function timeLabel(dateString) {
  const date = new Date(dateString)
  if (Number.isNaN(date.getTime())) {
    return 'just now'
  }

  return date.toLocaleString()
}

export default function ActivityFeed() {
  const [items, setItems] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    let cancelled = false

    async function load() {
      try {
        setLoading(true)
        const response = await window.axios.get('/api/dashboard/activity')
        if (!cancelled) {
          setItems(Array.isArray(response.data?.data) ? response.data.data : [])
        }
      } catch (err) {
        if (!cancelled) {
          setError('Could not load activity right now.')
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    load()

    return () => {
      cancelled = true
    }
  }, [])

  return (
    <section className="rounded-xl border border-gray-700 bg-gray-800 p-5 shadow-lg">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-semibold">Activity Feed</h2>
        <span className="text-xs text-gray-400">Recent actions</span>
      </div>

      {loading ? <p className="text-sm text-gray-400">Loading activity...</p> : null}
      {error ? <p className="text-sm text-rose-300">{error}</p> : null}

      {!loading && !error && items.length === 0 ? (
        <p className="text-sm text-gray-400">No recent activity yet.</p>
      ) : null}

      {!loading && !error && items.length > 0 ? (
        <div className="max-h-[520px] space-y-3 overflow-y-auto pr-1">
          {items.map((item) => (
            <article
              key={item.id}
              className={`rounded-xl border p-3 transition ${
                item.is_unread
                  ? 'border-cyan-500/40 bg-cyan-500/10'
                  : 'border-gray-700 bg-gray-900/60'
              }`}
            >
              <div className="flex items-start justify-between gap-2">
                <p className="text-sm text-gray-100">
                  <span className="font-semibold text-white">{actorLabel(item)}</span> {item.message}
                </p>
                {item.is_unread ? (
                  <span className="rounded-full bg-cyan-500/20 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-cyan-200">
                    unread
                  </span>
                ) : null}
              </div>
              <p className="mt-2 text-xs text-gray-400">{timeLabel(item.created_at)}</p>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
