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

function actorLabel(item) {
  if (!item?.user) {
    return 'Someone'
  }

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

function describeActivity(item) {
  const artworkTitle = item?.artwork?.title || 'an artwork'
  const mentionTarget = item?.mentioned_user?.username || item?.mentioned_user?.name || 'someone'
  const reactionLabel = item?.reaction?.label || 'reacted'

  switch (item?.type) {
    case 'comment':
      return `commented on ${artworkTitle}`
    case 'reply':
      return `replied on ${artworkTitle}`
    case 'reaction':
      return `${reactionLabel.toLowerCase()} on ${artworkTitle}`
    case 'mention':
      return `mentioned @${mentionTarget} on ${artworkTitle}`
    default:
      return 'shared new activity'
  }
}

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/activity', {
          params: {
            filter: 'my',
            per_page: 8,
          },
        })
        if (!cancelled) {
          setItems(Array.isArray(response.data?.data) ? response.data.data : [])
          setError('')
        }
      } 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> {describeActivity(item)}
                </p>
              </div>
              {item.comment?.body ? (
                <p className="mt-2 line-clamp-2 text-xs text-gray-300">{item.comment.body}</p>
              ) : null}
              <p className="mt-2 text-xs text-gray-400">{timeLabel(item.created_at)}</p>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
