// src/providers/UserDataProvider.tsx
import React, { useState, useEffect, useMemo, ReactNode } from 'react';
import { UserDataContext } from '../contexts/UserDataContext';
import type { MasterGroceryItem, ShoppingList } from '../types';
import * as apiClient from '../services/apiClient';
import { useApiOnMount } from '../hooks/useApiOnMount';
import { useAuth } from '../hooks/useAuth';

export const UserDataProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { user } = useAuth();
  
  const { data: watchedItemsData, loading: isLoadingWatched, error: watchedItemsError } = useApiOnMount<MasterGroceryItem[], []>(
    () => apiClient.fetchWatchedItems(), [user], { enabled: !!user }
  );
  const { data: shoppingListsData, loading: isLoadingShoppingLists, error: shoppingListsError } = useApiOnMount<ShoppingList[], []>(
    () => apiClient.fetchShoppingLists(), [user], { enabled: !!user }
  );

  const [watchedItems, setWatchedItems] = useState<MasterGroceryItem[]>([]);
  const [shoppingLists, setShoppingLists] = useState<ShoppingList[]>([]);

  // This effect synchronizes the local state (watchedItems, shoppingLists) with the
  // data fetched by the useApiOnMount hooks. It also handles cleanup on user logout.
  useEffect(() => {
    // When the user logs out (user becomes null), immediately clear all user-specific data.
    // This also serves to clear out old data when a new user logs in, before their new data arrives.
    if (!user) {
      setWatchedItems([]);
      setShoppingLists([]);
      return;
    }
    // Once data for the new user is fetched, update the state.
    if (watchedItemsData) setWatchedItems(watchedItemsData);
    if (shoppingListsData) setShoppingLists(shoppingListsData);
  }, [user, watchedItemsData, shoppingListsData]);

  const value = useMemo(() => ({
    watchedItems,
    shoppingLists,
    setWatchedItems,
    setShoppingLists,
    isLoading: !!user && (isLoadingWatched || isLoadingShoppingLists),
    error: watchedItemsError?.message || shoppingListsError?.message || null,
  }), [watchedItems, shoppingLists, user, isLoadingWatched, isLoadingShoppingLists, watchedItemsError, shoppingListsError]);

  return <UserDataContext.Provider value={value}>{children}</UserDataContext.Provider>;
};