import { useContext, useEffect, useState } from "react"; import { addStoreToHousehold, getAllStores, removeStoreFromHousehold, setDefaultStore } from "../../api/stores"; import { HouseholdContext } from "../../context/HouseholdContext"; import { StoreContext } from "../../context/StoreContext"; import "../../styles/components/manage/ManageStores.css"; export default function ManageStores() { const { activeHousehold } = useContext(HouseholdContext); const { stores: householdStores, refreshStores } = useContext(StoreContext); const [allStores, setAllStores] = useState([]); const [loading, setLoading] = useState(true); const [showAddStore, setShowAddStore] = useState(false); const isAdmin = activeHousehold?.role === "admin"; useEffect(() => { loadAllStores(); }, []); const loadAllStores = async () => { setLoading(true); try { const response = await getAllStores(); setAllStores(response.data); } catch (error) { console.error("Failed to load stores:", error); } finally { setLoading(false); } }; const handleAddStore = async (storeId) => { try { console.log("Adding store with ID:", storeId); await addStoreToHousehold(activeHousehold.id, storeId, false); await refreshStores(); setShowAddStore(false); } catch (error) { console.error("Failed to add store:", error); alert("Failed to add store"); } }; const handleRemoveStore = async (storeId, storeName) => { if (!confirm(`Remove ${storeName} from this household?`)) return; try { await removeStoreFromHousehold(activeHousehold.id, storeId); await refreshStores(); } catch (error) { console.error("Failed to remove store:", error); alert("Failed to remove store"); } }; const handleSetDefault = async (storeId) => { try { await setDefaultStore(activeHousehold.id, storeId); await refreshStores(); } catch (error) { console.error("Failed to set default store:", error); alert("Failed to set default store"); } }; const availableStores = allStores.filter( store => !householdStores.some(hs => hs.id === store.id) ); return (
{/* Current Stores Section */}

Your Stores ({householdStores.length})

{householdStores.length === 0 ? (

No stores added yet.

) : (
{householdStores.map((store) => (

{store.name}

{store.location &&

{store.location}

}
{isAdmin && (
{!store.is_default && ( )}
)}
))}
)}
{/* Add Store Section */} {isAdmin && (

Add Store

{!showAddStore ? ( ) : (
{loading ? (

Loading stores...

) : availableStores.length === 0 ? (

All available stores have been added.

) : (
{availableStores.map((store) => (

{store.name}

{store.location &&

{store.location}

}
))}
)}
)}
)}
); }