// ============================================================ // FoodTypeManagement.tsx – Updated by Ziad (Clean Version) // ============================================================ import { useState, useEffect, useCallback, useMemo } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { Textarea } from "./ui/textarea"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "./ui/select"; import { Badge } from "./ui/badge"; import { Wheat, Plus, Edit, Trash2, RefreshCw, Loader2, BellRing, } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "./ui/alert-dialog"; import Pagination from "@mui/material/Pagination"; import { User, Farm, BuoyancyType, ManufacturingProcess, GrowthStage, } from "../types"; import { mockFarms } from "../mockData"; import { apiGet, apiPost, apiPut, apiDelete } from "../api"; import { toast } from "sonner"; interface FoodTypeManagementProps { user: User; selectedFarm: Farm | null; } export default function FoodTypeManagement({ user, selectedFarm, }: FoodTypeManagementProps) { const currentFarm = selectedFarm || mockFarms[0]; const [showCreateModal, setShowCreateModal] = useState(false); const [editingId, setEditingId] = useState(null); const [saving, setSaving] = useState(false); const [deleteConfirmId, setDeleteConfirmId] = useState(null); const [foodTypes, setFoodTypes] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [currentPage, setCurrentPage] = useState(0); const ITEMS_PER_PAGE = 6; const [formData, setFormData] = useState({ name: "", arabicName: "", proteinPercentage: 30, fatPercentage: 6, fiberPercentage: 4, moisturePercentage: 10, ashPercentage: 12, pelletSizeMm: 3, buoyancyType: "FLOATING" as BuoyancyType, manufacturingProcess: "EXTRUDED" as ManufacturingProcess, applicableStages: [] as GrowthStage[], minFishWeightGrams: 0, maxFishWeightGrams: 0, shelfLifeDays: 180, storageInstructions: "", waterStabilityMinutes: 30, isActive: true, notes: "", lowStockThreshold: 100, }); const fetchFoodTypes = useCallback(async () => { setLoading(true); setError(null); try { const res = await apiGet("/aquaculture/food-types?limit=100"); const rawData = res.data || res || []; const normalizedData = Array.isArray(rawData) ? rawData.map((item: any) => ({ ...item, id: item.id || item._id, })) : []; setFoodTypes(normalizedData); setCurrentPage(0); } catch (err) { setError((err as Error).message); } finally { setLoading(false); } }, []); useEffect(() => { fetchFoodTypes(); }, [fetchFoodTypes]); const foodTypePages = useMemo(() => { const pages = []; for (let i = 0; i < foodTypes.length; i += ITEMS_PER_PAGE) { pages.push(foodTypes.slice(i, i + ITEMS_PER_PAGE)); } return pages; }, [foodTypes]); const currentFoodTypes = foodTypePages[currentPage] || []; const handleEdit = (foodType: any) => { setFormData({ ...foodType, lowStockThreshold: foodType.lowStockThreshold || 100, }); setEditingId(foodType.id); setShowCreateModal(true); }; const handleDelete = async () => { if (!deleteConfirmId) return; try { await apiDelete(`/aquaculture/food-types/${deleteConfirmId}`); toast.success("Food type deleted"); fetchFoodTypes(); } catch (err) { toast.error("Failed to delete: " + (err as Error).message); } finally { setDeleteConfirmId(null); } }; const handleSave = async () => { if (!formData.name || !formData.arabicName) { toast.error("الاسم والاسم العربي مطلوبين"); return; } setSaving(true); const { id, createdAt, updatedAt, deletedAt, ...submissionData } = formData as any; try { if (editingId) { await apiPut(`/aquaculture/food-types/${editingId}`, submissionData); } else { await apiPost("/aquaculture/food-types", submissionData); } toast.success("تم الحفظ بنجاح عبر الـ API"); fetchFoodTypes(); } catch (err) { console.warn("API Error - Switching to Mock Data:", err); const mockItem = { ...formData, id: editingId || Math.random().toString(36).substr(2, 9), }; if (editingId) { setFoodTypes((prev) => prev.map((item) => (item.id === editingId ? mockItem : item)), ); } else { setFoodTypes((prev) => [...prev, mockItem]); } toast.info("تمت الإضافة محلياً"); } finally { setSaving(false); setShowCreateModal(false); setEditingId(null); setFormData({ name: "", arabicName: "", proteinPercentage: 30, fatPercentage: 6, fiberPercentage: 4, moisturePercentage: 10, ashPercentage: 12, pelletSizeMm: 3, buoyancyType: "FLOATING", manufacturingProcess: "EXTRUDED", applicableStages: [], minFishWeightGrams: 0, maxFishWeightGrams: 0, shelfLifeDays: 180, storageInstructions: "", waterStabilityMinutes: 30, isActive: true, notes: "", lowStockThreshold: 100, }); } }; const isTechnician = user.role.toLowerCase() === "technician"; return (
Food Type Management

Fish Feed Products

Manage nutritional composition and inventory alert levels

{isTechnician && ( )}
{loading ? (
) : foodTypes.length === 0 ? (

No feed types registered yet.

) : ( currentFoodTypes.map((foodType) => (
{foodType.name}

{foodType.arabicName}

{foodType.lowStockThreshold || 100} kg
{foodType.proteinPercentage}% Protein {foodType.pelletSizeMm}mm {foodType.buoyancyType}
{isTechnician && (
)}
)) )}
{!loading && foodTypePages.length > 1 && (
setCurrentPage(page - 1)} color="primary" showFirstButton showLastButton />
)}

Basic Information

setFormData({ ...formData, name: e.target.value }) } />
setFormData({ ...formData, arabicName: e.target.value }) } />

Inventory Settings

setFormData({ ...formData, lowStockThreshold: parseInt(e.target.value) || 0, }) } />

Systems will alert when stock levels fall below this value.

Composition & Size

setFormData({ ...formData, proteinPercentage: parseFloat(e.target.value), }) } />
setFormData({ ...formData, fatPercentage: parseFloat(e.target.value), }) } />
setFormData({ ...formData, pelletSizeMm: parseFloat(e.target.value), }) } />
setDeleteConfirmId(null)} > Delete Product? This action will remove the feed type from the catalogue permanently. Cancel Delete
); }