import React, { useState, useEffect, useCallback } from "react"; import { Box, Typography, Skeleton, useTheme, Button } from "@mui/material"; import MealCard from "./MealCard"; import authService from "../../../../services/authService"; import AddMeal from "./AddMeal"; import SimplePagination from "../../SimplePagination"; const MealsByCateg = ({ restaurantId, categoryId, onProductClick, onAddMeal, categoryName, onBack, }) => { const theme = useTheme(); const [products, setProducts] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [openModal, setOpenModal] = useState(false); const [page, setPage] = useState(1); const [pagination, setPagination] = useState(null); const itemsPerPage = 6; // استخدام useCallback لمنع إنشاء الدالة عند كل إعادة render const fetchMeals = useCallback(async () => { if (!restaurantId || !categoryId) return; setLoading(true); setError(null); try { const result = await authService.getMealsByCategory( restaurantId, categoryId, page ); if (result.success) { const mealsWithImages = result.data.map((meal) => ({ id: meal.id, name: meal.name, price: meal.price, description: meal.description || [], additions: meal.additions || [], unit: meal.unit || "/pcs", photo: meal.photo || "/images/default-product.png", category_id: meal.category_id || categoryId, })); setProducts(mealsWithImages); setPagination(result.pagination); } else { setProducts([]); setPagination(null); } } catch (err) { console.error(err); setError("Failed to fetch meals."); setProducts([]); setPagination(null); } finally { setLoading(false); } }, [restaurantId, categoryId, page]); // جلب البيانات عند تغيير restaurantId أو categoryId أو page useEffect(() => { fetchMeals(); }, [fetchMeals]); // إضافة وجبة جديدة وتحديث القائمة فورًا // في MealsByCateg const handleAddProduct = async (meal) => { setOpenModal(false); // اغلاق مودال الإضافة setPage(1); // العودة للصفحة الأولى const result = await fetchMeals(); // جلب الوجبات بعد الإضافة if (onAddMeal) onAddMeal(meal); // تمرير الوجبة للمكون الأب }; return ( {/* العنوان + أزرار */} {categoryName || "Meals"} {/* حالة التحميل أو الخطأ */} {loading ? ( {Array.from({ length: itemsPerPage }).map((_, index) => ( ))} ) : error ? ( {error} ) : products.length === 0 ? ( There is no meal available ) : ( {products.map((product) => ( onProductClick({ ...product, category: categoryName, category_id: categoryId, }) } > onProductClick({ ...product, category: categoryName, category_id: categoryId, }) } onAdd={onAddMeal} /> ))} )} {/* Pagination Footer */} {pagination && !loading && pagination.last_page > 1 && ( Showing {(page - 1) * itemsPerPage + 1} to{" "} {Math.min(page * itemsPerPage, pagination.total)} of {pagination.total} meals setPage(newPage)} /> )} {/* Add Meal Modal */} setOpenModal(false)} onAdd={handleAddProduct} selectedCategory={categoryId} restaurantId={restaurantId} /> ); }; export default MealsByCateg;