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

function actorLabel(item) {
  if (!item?.actor) {
    return item?.type === 'notification' ? 'System' : 'Someone'
  }

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

function describeActivity(item) {
  switch (item?.type) {
    case 'comment':
      return item?.context?.artwork_title ? `commented on ${item.context.artwork_title}` : 'commented on your artwork'
    case 'new_follower':
      return 'started following you'
    case 'notification':
      return item?.message || 'sent a notification'
    default:
      return item?.message || 'shared new activity'
  }
}

function activityIcon(type) {
  switch (type) {
    case 'comment':
      return 'fa-solid fa-comment-dots'
    case 'new_follower':
      return 'fa-solid fa-user-plus'
    case 'notification':
      return 'fa-solid fa-bell'
    default:
      return 'fa-solid fa-bolt'
  }
}

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-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.82))] p-5 shadow-[0_24px_90px_rgba(2,8,23,0.32)]">
      <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <p className="text-[11px] uppercase tracking-[0.24em] text-sky-200/70">Live activity</p>
          <h2 className="mt-2 text-xl font-semibold text-white">Activity Feed</h2>
          <p className="mt-2 max-w-xl text-sm leading-6 text-slate-300">
            Recent followers, artwork comments, and notifications that deserve your attention.
          </p>
        </div>
        <span className="inline-flex items-center justify-center rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-slate-300 sm:justify-start">Recent actions</span>
      </div>

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

      {!loading && !error && items.length === 0 ? (
        <div className="rounded-2xl border border-white/8 bg-white/5 px-5 py-6 text-sm text-slate-300">
          <p className="font-medium text-white">No recent activity yet.</p>
          <p className="mt-2 text-slate-400">New followers, comments, and notifications will appear here as they happen.</p>
        </div>
      ) : null}

      {!loading && !error && items.length > 0 ? (
        <div className="nova-scrollbar max-h-[520px] space-y-3 overflow-y-auto pr-2">
          {items.map((item) => (
            <article
              key={item.id}
              className={`rounded-xl border p-3 transition ${
                item.is_unread
                  ? 'border-sky-400/30 bg-sky-400/10'
                  : 'border-white/8 bg-white/[0.04]'
              }`}
            >
              <div className="flex items-start gap-3">
                <div className="flex h-11 w-11 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-slate-950/60">
                  {item.actor?.avatar ? (
                    <img src={item.actor.avatar} alt={actorLabel(item)} className="h-full w-full object-cover" />
                  ) : (
                    <i className={`${activityIcon(item.type)} text-sm text-sky-100/80`} />
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                      <p className="text-sm text-slate-100">
                        <span className="font-semibold text-white">{actorLabel(item)}</span>{' '}
                        <span>{describeActivity(item)}</span>
                      </p>
                      {item.message && item.type !== 'notification' ? (
                        <p className="mt-1 text-xs text-slate-400">{item.message}</p>
                      ) : null}
                    </div>
                    <span className="text-[11px] uppercase tracking-wide text-slate-400 sm:shrink-0">{timeLabel(item.created_at)}</span>
                  </div>

                  {item.context?.artwork_url ? (
                    <a
                      href={item.context.artwork_url}
                      className="mt-3 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-slate-200 transition hover:border-white/20 hover:bg-white/10"
                    >
                      View artwork
                      <i className="fa-solid fa-arrow-right text-[10px]" />
                    </a>
                  ) : null}
                </div>
              </div>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
