import { useState, useEffect, useCallback } from 'react';
import { bookmarkApi, BookmarkItem } from '@/services/bookmarkApi';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

export const useBookmarks = () => {
  const { user } = useAuth();
  const [bookmarks, setBookmarks] = useState<BookmarkItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load bookmarks
  const loadBookmarks = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const bookmarksData = await bookmarkApi.getBookmarks(user?.id);
      setBookmarks(bookmarksData);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load bookmarks';
      setError(errorMessage);
      console.error('Error loading bookmarks:', err);
    } finally {
      setLoading(false);
    }
  }, [user?.id]);

  // Add bookmark
  const addBookmark = useCallback(async (itemId: string): Promise<boolean> => {
    if (!user?.id) {
      toast.error('Please sign in to bookmark items');
      return false;
    }

    try {
      const success = await bookmarkApi.addBookmark(itemId, user.id);
      if (success) {
        toast.success('Added to bookmarks');
        // Reload bookmarks to get updated list
        await loadBookmarks();
        return true;
      } else {
        toast.error('Failed to add bookmark');
        return false;
      }
    } catch (err) {
      console.error('Error adding bookmark:', err);
      toast.error('Failed to add bookmark');
      return false;
    }
  }, [user?.id, loadBookmarks]);

  // Remove bookmark
  const removeBookmark = useCallback(async (itemId: string): Promise<boolean> => {
    if (!user?.id) {
      toast.error('Please sign in to manage bookmarks');
      return false;
    }

    try {
      const success = await bookmarkApi.removeBookmark(itemId, user.id);
      if (success) {
        toast.success('Removed from bookmarks');
        // Remove from local state immediately for better UX
        setBookmarks(prev => prev.filter(bookmark => bookmark.id !== itemId));
        return true;
      } else {
        toast.error('Failed to remove bookmark');
        return false;
      }
    } catch (err) {
      console.error('Error removing bookmark:', err);
      toast.error('Failed to remove bookmark');
      return false;
    }
  }, [user?.id]);

  // Check if item is bookmarked
  const isBookmarked = useCallback((itemId: string): boolean => {
    return bookmarks.some(bookmark => bookmark.id === itemId);
  }, [bookmarks]);

  // Toggle bookmark status
  const toggleBookmark = useCallback(async (itemId: string): Promise<boolean> => {
    const bookmarked = isBookmarked(itemId);
    
    if (bookmarked) {
      return await removeBookmark(itemId);
    } else {
      return await addBookmark(itemId);
    }
  }, [isBookmarked, addBookmark, removeBookmark]);

  // Get bookmark by ID
  const getBookmarkById = useCallback((itemId: string): BookmarkItem | undefined => {
    return bookmarks.find(bookmark => bookmark.id === itemId);
  }, [bookmarks]);

  // Filter bookmarks by category
  const getBookmarksByCategory = useCallback((category: string): BookmarkItem[] => {
    return bookmarks.filter(bookmark => 
      bookmark.category.toLowerCase() === category.toLowerCase()
    );
  }, [bookmarks]);

  // Get bookmarks count
  const getBookmarksCount = useCallback((): number => {
    return bookmarks.length;
  }, [bookmarks]);

  // Clear error
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  // Initial load
  useEffect(() => {
    if (user?.id) {
      loadBookmarks();
    }
  }, [loadBookmarks, user?.id]);

  return {
    bookmarks,
    loading,
    error,
    loadBookmarks,
    addBookmark,
    removeBookmark,
    toggleBookmark,
    isBookmarked,
    getBookmarkById,
    getBookmarksByCategory,
    getBookmarksCount,
    clearError
  };
};