import { useState, useEffect, useRef, useCallback } from "react";
import { FeedItem, loadFeeds } from "../services/feedService";
import { TopicFeedConfig } from "../config/topicFeedConfig";

interface UseTopicFeedResult {
  feedItems: FeedItem[];
  initialLoading: boolean;
  loadingMore: boolean;
  error: string | null;
  hasMore: boolean;
  loadMore: () => void;
  deletePost: (postId: string) => void;
}

export const useTopicFeed = (topic: TopicFeedConfig | null): UseTopicFeedResult => {
  const [feedItems, setFeedItems] = useState<FeedItem[]>([]);
  const [initialLoading, setInitialLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const fetchLockRef = useRef(false);
  const currentTopicRef = useRef<string | null>(null);

  const fetchFeeds = useCallback(
    async (page: number, isInitial: boolean) => {
      if (!topic || !topic.hasFeed) {
        setInitialLoading(false);
        return;
      }

      if (fetchLockRef.current) return;

      fetchLockRef.current = true;

      if (isInitial) {
        setInitialLoading(true);
      } else {
        setLoadingMore(true);
      }

      setError(null);

      try {
        const result = await loadFeeds(topic.serverName, page);

        if (currentTopicRef.current !== topic.serverName) {
          return;
        }

        if (result.success) {
          const newItems = result.data;

          if (newItems.length === 0 || newItems.length < 25) {
            setHasMore(false);
          }

          if (isInitial) {
            setFeedItems(newItems);
          } else {
            setFeedItems((prev) => {
              const existingIds = new Set(prev.map((item) => item.StageID));
              const uniqueNewItems = newItems.filter(
                (item) => !existingIds.has(item.StageID)
              );
              return [...prev, ...uniqueNewItems];
            });
          }
        } else {
          setError(result.message || "خطا در بارگذاری فید");
        }
      } catch (err) {
        if (currentTopicRef.current === topic.serverName) {
          setError("خطا در ارتباط با سرور");
        }
      } finally {
        if (currentTopicRef.current === topic.serverName) {
          setInitialLoading(false);
          setLoadingMore(false);
        }
        fetchLockRef.current = false;
      }
    },
    [topic]
  );

  useEffect(() => {
    if (!topic) {
      setInitialLoading(false);
      return;
    }

    currentTopicRef.current = topic.serverName;
    setFeedItems([]);
    setCurrentPage(1);
    setHasMore(true);
    setError(null);
    fetchFeeds(1, true);

    return () => {
      currentTopicRef.current = null;
    };
  }, [topic, fetchFeeds]);

  const loadMore = useCallback(() => {
    if (!hasMore || loadingMore || initialLoading) return;

    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    fetchFeeds(nextPage, false);
  }, [hasMore, loadingMore, initialLoading, currentPage, fetchFeeds]);

  const deletePost = useCallback((postId: string) => {
    setFeedItems((prev) => prev.filter((item) => item.StageID.toString() !== postId));
  }, []);

  return {
    feedItems,
    initialLoading,
    loadingMore,
    error,
    hasMore,
    loadMore,
    deletePost,
  };
};
