import { useState, useCallback, useEffect } from 'react';
import { FeedItem } from '@/types/feed';
import { getAllFeedItems } from '@/services/database';

const PAGE_SIZE = 20;

export function useFeedList() {
  const [localFeedItems, setLocalFeedItems] = useState<FeedItem[]>([]);
  const [page, setPage] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadMore = useCallback(async () => {
    if (loadingMore || !hasMore || isRefreshing) return;
    
    setLoadingMore(true);
    
    try {
      const offset = page * PAGE_SIZE;
      const items = await getAllFeedItems(PAGE_SIZE + 1, offset);
      
      if (items.length > PAGE_SIZE) {
        const newItems = items.slice(0, PAGE_SIZE);
        setLocalFeedItems(prev => [...prev, ...newItems]);
        setHasMore(true);
      } else {
        setLocalFeedItems(prev => [...prev, ...items]);
        setHasMore(false);
      }
      
      setPage(prev => prev + 1);
      setError(null);
    } catch (err) {
      console.error('Failed to load more items:', err);
      setError('Failed to load more items. Please try again.');
    } finally {
      setLoadingMore(false);
    }
  }, [loadingMore, hasMore, isRefreshing, page]);

  const refreshFeed = useCallback(async () => {
    if (isRefreshing) return;
    
    setIsRefreshing(true);
    setPage(0);
    setHasMore(true);
    setError(null);
    
    try {
      const items = await getAllFeedItems(PAGE_SIZE + 1);
      
      if (items.length > PAGE_SIZE) {
        setLocalFeedItems(items.slice(0, PAGE_SIZE));
        setHasMore(true);
      } else {
        setLocalFeedItems(items);
        setHasMore(false);
      }
    } catch (err) {
      console.error('Failed to refresh feed:', err);
      setError('Failed to refresh feed. Please try again.');
    } finally {
      setIsRefreshing(false);
    }
  }, [isRefreshing]);

  useEffect(() => {
    refreshFeed();
  }, []);

  return {
    feedItems: localFeedItems,
    loading: loadingMore,
    hasMore,
    loadMore,
    refreshFeed,
    isRefreshing,
    error,
  };
}
