import React, { useState, useEffect, useCallback } from 'react'
import { usePage } from '@inertiajs/react'
import axios from 'axios'
import SeoHead from '../../components/seo/SeoHead'
import PostCard        from '../../Components/Feed/PostCard'
import PostCardSkeleton from '../../Components/Feed/PostCardSkeleton'

function TrendingHashtagsSidebar({ hashtags, activeTag = null }) {
  if (!hashtags || hashtags.length === 0) return null
  return (
    <div className="rounded-2xl border border-white/[0.07] bg-white/[0.03] overflow-hidden">
      <div className="flex items-center gap-2 px-4 py-3 border-b border-white/[0.05]">
        <i className="fa-solid fa-hashtag text-slate-500 fa-fw text-[13px]" />
        <span className="text-[11px] font-semibold uppercase tracking-widest text-slate-500">Trending Tags</span>
      </div>
      <div className="px-4 py-3 space-y-1.5">
        {hashtags.map((h) => (
          <a
            key={h.tag}
            href={`/tags/${h.tag}`}
            className={`flex items-center justify-between group px-2 py-1.5 rounded-lg transition-colors ${
              activeTag === h.tag
                ? 'bg-sky-500/15 text-sky-400'
                : 'hover:bg-white/5 text-slate-400 hover:text-white'
            }`}
          >
            <span className="text-sm font-medium">#{h.tag}</span>
            <span className="text-[11px] text-slate-600 group-hover:text-slate-500 tabular-nums">
              {h.post_count} posts
            </span>
          </a>
        ))}
      </div>
    </div>
  )
}

export default function TrendingFeed() {
  const { props }            = usePage()
  const { auth, trendingHashtags, seo } = props
  const authUser             = auth?.user ?? null

  const [posts,   setPosts]   = useState([])
  const [loading, setLoading] = useState(true)
  const [page,    setPage]    = useState(1)
  const [hasMore, setHasMore] = useState(false)
  const [loaded,  setLoaded]  = useState(false)

  const fetchFeed = useCallback(async (p = 1) => {
    setLoading(true)
    try {
      const { data } = await axios.get('/api/feed/trending', { params: { page: p } })
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data])
      setHasMore(data.meta.current_page < data.meta.last_page)
      setPage(p)
    } catch {
      //
    } finally {
      setLoading(false)
      setLoaded(true)
    }
  }, [])

  useEffect(() => { fetchFeed(1) }, [])

  const handleDeleted = useCallback((id) => setPosts((prev) => prev.filter((p) => p.id !== id)), [])

  return (
    <>
      <SeoHead seo={seo} />
      <div className="min-h-screen bg-[#080f1e]">
      <div className="max-w-5xl mx-auto px-4 pt-8 pb-16">
        <div className="flex gap-8">
          {/* ── Main feed ──────────────────────────────────────────────── */}
          <div className="flex-1 min-w-0 space-y-4">
            <div className="mb-6">
              <h1 className="text-xl font-bold text-white">
                <i className="fa-solid fa-fire mr-2 text-orange-400 opacity-80" />
                Trending
              </h1>
              <p className="text-sm text-slate-500 mt-0.5">Most engaging posts right now</p>
            </div>

            {!loaded && loading && (
              <>{Array.from({ length: 3 }).map((_, i) => <PostCardSkeleton key={i} />)}</>
            )}

            {loaded && !loading && posts.length === 0 && (
              <div className="flex flex-col items-center justify-center py-24 text-center">
                <div className="w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600">
                  <i className="fa-solid fa-fire text-2xl" />
                </div>
                <h2 className="text-lg font-semibold text-white/80 mb-2">Nothing trending yet</h2>
                <p className="text-slate-500 text-sm">Check back soon — posts are ranked by engagement.</p>
              </div>
            )}

            {posts.map((post) => (
              <PostCard
                key={post.id}
                post={post}
                isLoggedIn={!!authUser}
                viewerUsername={authUser?.username ?? null}
                onDelete={handleDeleted}
              />
            ))}

            {loaded && hasMore && (
              <div className="flex justify-center py-4">
                <button
                  onClick={() => fetchFeed(page + 1)}
                  disabled={loading}
                  className="px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors disabled:opacity-50"
                >
                  {loading
                    ? <><i className="fa-solid fa-spinner fa-spin mr-2" />Loading…</>
                    : 'Load more'}
                </button>
              </div>
            )}
          </div>

          {/* ── Sidebar ────────────────────────────────────────────────── */}
          <aside className="hidden lg:block w-64 shrink-0 space-y-4 pt-14">
            <TrendingHashtagsSidebar hashtags={trendingHashtags} />
            <div className="rounded-2xl border border-white/[0.07] bg-white/[0.03] px-4 py-4 text-center">
              <p className="text-xs text-slate-500 leading-relaxed">
                Posts are ranked by likes, comments &amp; engagement over the last 7 days.
              </p>
            </div>
          </aside>
        </div>
      </div>
    </div>
    </>
  )
}
