import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { FiHome } from "react-icons/fi";
import Post from "@/components/social/posts/Post";
import PostComposer from "@/components/social/posts/PostComposer";
import EmptyState from "@/components/ui/EmptyState";
import Spinner from "@/components/ui/Spinner";
import { useInfinitePosts } from "@/hooks/useInfinitePosts";
import { useIntersectionLoader } from "@/hooks/useIntersectionLoader";

export default function FeedPage() {
  const { t } = useTranslation("social");
  const navigate = useNavigate();
  const {
    posts,
    isLoading,
    isError,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
  } = useInfinitePosts();

  const sentinelRef = useIntersectionLoader<HTMLDivElement>(
    () => {
      if (hasNextPage && !isFetchingNextPage) void fetchNextPage();
    },
    { enabled: hasNextPage && !isLoading },
  );

  return (
    <div>
      <header className="sticky top-0 z-10 border-b border-brand-lines/10 bg-brand-bg/80 px-4 py-3 backdrop-blur">
        <h1 className="text-lg font-bold text-brand-text">{t("feed.title")}</h1>
      </header>

      <PostComposer />

      {isLoading && (
        <div className="flex justify-center py-10">
          <Spinner size={28} />
        </div>
      )}

      {isError && !isLoading && (
        <EmptyState
          title={t("common:error", { defaultValue: "Něco se nepovedlo" })}
          action={
            <button
              type="button"
              onClick={() => void refetch()}
              className="text-brand-accent hover:underline"
            >
              {t("common:retry", { defaultValue: "Zkusit znovu" })}
            </button>
          }
        />
      )}

      {!isLoading && !isError && posts.length === 0 && (
        <EmptyState icon={<FiHome />} message={t("feed.empty")} />
      )}

      <div>
        {posts.map((p) => (
          <Post
            key={p.id}
            post={p}
            onReplyClick={() => navigate(`/social/post/${p.id}`)}
          />
        ))}
      </div>

      {hasNextPage && (
        <div
          ref={sentinelRef}
          className="flex items-center justify-center py-6 text-sm text-brand-text/60"
        >
          {isFetchingNextPage ? <Spinner size={20} /> : t("feed.loadingMore")}
        </div>
      )}
    </div>
  );
}
