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

export default function HashtagFeed() {
  const { props }      = usePage()
  const { auth, tag }  = 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 [totalPosts, setTotalPosts] = useState(null)

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

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

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

  return (
    <div className="min-h-screen bg-[#080f1e]">
      <div className="max-w-2xl mx-auto px-4 pt-8 pb-16">
        {/* Header */}
        <div className="mb-6">
          <div className="flex items-center gap-3 mb-1">
            <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl bg-sky-500/15 text-sky-400 text-lg font-bold">
              #
            </span>
            <div>
              <h1 className="text-xl font-bold text-white">#{tag}</h1>
              {totalPosts !== null && (
                <p className="text-sm text-slate-500 mt-0.5">
                  {totalPosts.toLocaleString()} post{totalPosts !== 1 ? 's' : ''}
                </p>
              )}
            </div>
          </div>
          <div className="mt-4 flex gap-2">
            <a
              href="/feed/trending"
              className="text-xs text-slate-500 hover:text-sky-400 transition-colors"
            >
              ← Trending
            </a>
          </div>
        </div>

        {/* Feed */}
        <div className="space-y-4">
          {!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-hashtag text-2xl" />
              </div>
              <h2 className="text-lg font-semibold text-white/80 mb-2">No posts yet</h2>
              <p className="text-slate-500 text-sm max-w-xs">
                No posts tagged <span className="text-sky-400">#{tag}</span> yet. Be the first!
              </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>
      </div>
    </div>
  )
}
