import { useEffect, useMemo, useState } from "react"; import { Badge } from "./ui/badge"; import { Button } from "./ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "./ui/dialog"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { Switch } from "./ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs"; import { Textarea } from "./ui/textarea"; import { AlertCircle, Fish, Loader2, Plus, RefreshCcw, Trash2, Wheat, } from "lucide-react"; import { Farm, User } from "../types"; import { FishGradePricingRecord, getPricingByFishType, } from "../services/harvestApi"; import { ExpectedGradeDistributionEntry, FeedingRateMatrix, FeedingRateResult, FishTypeRecord, FishTypeUpsertPayload, FoodTypeOption, ProteinRequirementResult, ProteinRequirementRule, createFishType, getFeedingRate, getFishTypeById, getFishTypes, getFoodTypes, getProteinRequirement, updateFishType, } from "../services/fishTypesApi"; import Pagination from "@mui/material/Pagination"; interface FishTypeManagementProps { user: User; selectedFarm: Farm | null; } type FormTab = "basic" | "water" | "feeding" | "protein" | "food"; interface FishTypeFormState { name: string; scientificName: string; arabicName: string; description: string; tempMin: number; tempMax: number; doMin: number; doMax: number; phMin: number; phMax: number; nh3Min: number; nh3Max: number; no2Min: number; no2Max: number; turbidityMin: number; turbidityMax: number; fcrMin: number; fcrMax: number; survivalRate: number; targetSGR: number; targetWeightForHarvest: number; defaultMarketPrice: number; criticalParameters: string[]; feedingRateMatrix: FeedingRateMatrix; proteinRequirements: ProteinRequirementRule[]; expectedGradeDistribution: ExpectedGradeDistributionEntry[]; notes: string; allowedFoodTypeIds: string[]; isActive: boolean; } const CRITICAL_PARAMETER_OPTIONS = [ "Temperature", "Dissolved Oxygen", "pH", "Ammonia", "Nitrite", "Turbidity", ]; const createDefaultFeedingRateMatrix = (): FeedingRateMatrix => ({ weight_ranges: [ { min: 10, max: 15 }, { min: 15, max: 20 }, { min: 20, max: 30 }, ], temperatures: [18, 23, 26, 30], rates: [ [2.0, 3.0, 4.25, 4.5], [2.0, 2.75, 4.0, 4.25], [1.8, 2.5, 3.75, 4.0], ], }); // Meal defaults removed const createDefaultProteinRequirements = (): ProteinRequirementRule[] => [ { minWeight: 0, maxWeight: 10, proteinPercentage: 35 }, { minWeight: 10, maxWeight: 50, proteinPercentage: 32 }, { minWeight: 50, maxWeight: 200, proteinPercentage: 30 }, { minWeight: 200, maxWeight: null, proteinPercentage: 28 }, ]; const cloneFeedingRateMatrix = ( matrix: FeedingRateMatrix, ): FeedingRateMatrix => ({ weight_ranges: matrix.weight_ranges.map((range) => ({ min: range.min, max: range.max, })), temperatures: [...matrix.temperatures], rates: matrix.rates.map((row) => [...row]), }); const normalizeFeedingRateMatrix = ( matrix: FeedingRateMatrix, ): FeedingRateMatrix => { const temperatures = matrix.temperatures.length > 0 ? [...matrix.temperatures] : [20, 24, 28]; const weightRanges = matrix.weight_ranges.length > 0 ? matrix.weight_ranges.map((range) => ({ min: range.min ?? 0, max: range.max ?? 0, })) : [{ min: 0, max: 10 }]; const rates = weightRanges.map((_, rowIndex) => temperatures.map((_, colIndex) => { const value = matrix.rates[rowIndex]?.[colIndex]; return Number.isFinite(value) ? value : 0; }), ); return { weight_ranges: weightRanges, temperatures, rates, }; }; const getDefaultFormState = (): FishTypeFormState => ({ name: "", scientificName: "", arabicName: "", description: "", tempMin: 20, tempMax: 32, doMin: 3, doMax: 8, phMin: 6.5, phMax: 8.5, nh3Min: 0, nh3Max: 0.05, no2Min: 0, no2Max: 0.2, turbidityMin: 0, turbidityMax: 10, fcrMin: 1.2, fcrMax: 1.8, survivalRate: 85, targetSGR: 2, targetWeightForHarvest: 0, defaultMarketPrice: 0, criticalParameters: ["DO", "NH3", "Temperature"], feedingRateMatrix: createDefaultFeedingRateMatrix(), proteinRequirements: createDefaultProteinRequirements(), expectedGradeDistribution: [], notes: "", allowedFoodTypeIds: [], isActive: true, }); const toFormState = (fishType: FishTypeRecord): FishTypeFormState => ({ name: fishType.name, scientificName: fishType.scientificName, arabicName: fishType.arabicName || "", description: fishType.description || "", tempMin: fishType.tempMin, tempMax: fishType.tempMax, doMin: fishType.doMin, doMax: fishType.doSafe || 0, phMin: fishType.phMin, phMax: fishType.phMax, nh3Min: fishType.nh3Safe || 0, nh3Max: fishType.nh3Critical || 0, no2Min: 0, no2Max: fishType.no2Max, turbidityMin: fishType.turbidityMin || 0, turbidityMax: fishType.turbidityMax || 0, fcrMin: fishType.fcrMin, fcrMax: fishType.fcrMax, survivalRate: fishType.survivalRate, targetSGR: fishType.targetSGR ?? 0, targetWeightForHarvest: fishType.targetWeightForHarvest ?? 0, defaultMarketPrice: fishType.defaultMarketPrice ?? 0, criticalParameters: fishType.criticalParameters, feedingRateMatrix: normalizeFeedingRateMatrix(fishType.feedingRateMatrix), proteinRequirements: fishType.proteinRequirements.length > 0 ? fishType.proteinRequirements.map((rule) => ({ minWeight: rule.minWeight, maxWeight: rule.maxWeight, proteinPercentage: rule.proteinPercentage, })) : createDefaultProteinRequirements(), expectedGradeDistribution: fishType.expectedGradeDistribution || [], notes: fishType.notes || "", allowedFoodTypeIds: fishType.allowedFoodTypeIds, isActive: fishType.isActive, }); const toNumber = (value: string): number => { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : 0; }; const toNullableNumber = (value: string): number | null => { const normalized = value.trim(); if (!normalized) { return null; } const parsed = Number(normalized); if (!Number.isFinite(parsed)) { return null; } return parsed; }; const calculateDistributionTotal = ( entries: ExpectedGradeDistributionEntry[], ): number => entries.reduce( (sum, entry) => sum + (Number.isFinite(entry.percentage) ? entry.percentage : 0), 0, ); const validateForm = (form: FishTypeFormState): string | null => { if (!form.name.trim() || !form.scientificName.trim()) { return "Name and scientific name are required."; } if ( form.feedingRateMatrix.weight_ranges.length === 0 || form.feedingRateMatrix.temperatures.length === 0 ) { return "Feeding matrix must include at least one weight range and one temperature."; } const invalidRange = form.feedingRateMatrix.weight_ranges.find( (range) => range.min === null || range.max === null || range.max <= range.min, ); if (invalidRange) { return "Each feeding weight range must have a maximum greater than minimum."; } const invalidRateShape = form.feedingRateMatrix.rates.some( (row) => row.length !== form.feedingRateMatrix.temperatures.length, ); if ( invalidRateShape || form.feedingRateMatrix.rates.length !== form.feedingRateMatrix.weight_ranges.length ) { return "Feeding matrix rates must align with all weight ranges and temperatures."; } // Meal validation removed const invalidProtein = form.proteinRequirements.some( (rule) => !Number.isFinite(rule.proteinPercentage) || rule.proteinPercentage <= 0, ); if (invalidProtein) { return "Each protein requirement rule must have protein percentage greater than 0."; } if (form.expectedGradeDistribution.length > 0) { const invalidDistributionRow = form.expectedGradeDistribution.some( (row) => !row.gradePricingId.trim() || !Number.isFinite(row.percentage) || row.percentage <= 0, ); if (invalidDistributionRow) { return "Each expected grade distribution row needs grade pricing id and percentage > 0."; } const total = calculateDistributionTotal(form.expectedGradeDistribution); if (Math.abs(total - 100) > 0.01) { return "Expected grade distribution percentages must sum to 100."; } } return null; }; const toUpsertPayload = (form: FishTypeFormState): FishTypeUpsertPayload => ({ name: form.name.trim(), scientificName: form.scientificName.trim(), arabicName: form.arabicName.trim() || undefined, description: form.description.trim() || undefined, tempMin: form.tempMin, tempOptimal: (form.tempMin + form.tempMax) / 2, tempMax: form.tempMax, doMin: form.doMin, doSafe: form.doMax, phMin: form.phMin, phMax: form.phMax, nh3Safe: form.nh3Min, nh3Critical: form.nh3Max, no2Max: form.no2Max, turbidityMin: form.turbidityMin, turbidityMax: form.turbidityMax, fcrMin: form.fcrMin, fcrMax: form.fcrMax, survivalRate: form.survivalRate, targetSGR: form.targetSGR, targetWeightForHarvest: form.targetWeightForHarvest, defaultMarketPrice: form.defaultMarketPrice, feedingRateMatrix: cloneFeedingRateMatrix(form.feedingRateMatrix), proteinRequirements: form.proteinRequirements.map((rule) => ({ minWeight: rule.minWeight, maxWeight: rule.maxWeight, proteinPercentage: rule.proteinPercentage, })), criticalParameters: form.criticalParameters, expectedGradeDistribution: form.expectedGradeDistribution.length > 0 ? form.expectedGradeDistribution.map((row) => ({ gradePricingId: row.gradePricingId.trim(), percentage: row.percentage, })) : undefined, notes: form.notes.trim() || undefined, allowedFoodTypeIds: form.allowedFoodTypeIds.length > 0 ? form.allowedFoodTypeIds : undefined, isActive: form.isActive, }); export default function FishTypeManagementEnhanced({ user, selectedFarm, }: FishTypeManagementProps) { const [fishTypes, setFishTypes] = useState([]); const [foodTypes, setFoodTypes] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isRefreshing, setIsRefreshing] = useState(false); const [isLoadingFoodTypes, setIsLoadingFoodTypes] = useState(false); const [isLoadingGradePricing, setIsLoadingGradePricing] = useState(false); const [errorMessage, setErrorMessage] = useState(null); const [gradePricingError, setGradePricingError] = useState( null, ); const [foodTypePage, setFoodTypePage] = useState(0); const [isModalOpen, setIsModalOpen] = useState(false); const [activeFormTab, setActiveFormTab] = useState("basic"); const [editingFishTypeId, setEditingFishTypeId] = useState( null, ); const [isSaving, setIsSaving] = useState(false); const [formError, setFormError] = useState(null); const [formState, setFormState] = useState( getDefaultFormState(), ); const [gradePricingOptions, setGradePricingOptions] = useState< FishGradePricingRecord[] >([]); const [calculatorFishTypeId, setCalculatorFishTypeId] = useState(""); const [calculatorWeight, setCalculatorWeight] = useState(45); const [calculatorTemperature, setCalculatorTemperature] = useState(27); const [isRunningCalculator, setIsRunningCalculator] = useState(false); const [calculatorError, setCalculatorError] = useState(null); const [feedingRateResult, setFeedingRateResult] = useState(null); // Meal frequency state removed const [proteinRequirementResult, setProteinRequirementResult] = useState(null); const currentFarmLabel = selectedFarm?.name || "Current Farm"; const distributionTotal = useMemo( () => calculateDistributionTotal(formState.expectedGradeDistribution), [formState.expectedGradeDistribution], ); const loadFishTypes = async (silent = false) => { if (silent) { setIsRefreshing(true); } else { setIsLoading(true); } setErrorMessage(null); try { const list = await getFishTypes(false); setFishTypes(list); if (!calculatorFishTypeId && list.length > 0) { setCalculatorFishTypeId(list[0].id); } } catch (error) { setErrorMessage( error instanceof Error ? error.message : "Failed to load fish types.", ); setFishTypes([]); } finally { setIsLoading(false); setIsRefreshing(false); } }; const loadFoodTypes = async () => { setIsLoadingFoodTypes(true); try { const list = await getFoodTypes(); setFoodTypes(list); } catch (error) { setErrorMessage( error instanceof Error ? error.message : "Failed to load food types.", ); setFoodTypes([]); } finally { setIsLoadingFoodTypes(false); } }; useEffect(() => { void Promise.all([loadFishTypes(), loadFoodTypes()]); }, []); const openCreateModal = () => { setEditingFishTypeId(null); setFormError(null); setActiveFormTab("basic"); setFormState(getDefaultFormState()); setGradePricingOptions([]); setGradePricingError(null); setFoodTypePage(0); setIsModalOpen(true); }; const openEditModal = async (fishTypeId: string) => { setEditingFishTypeId(fishTypeId); setFormError(null); setGradePricingError(null); setGradePricingOptions([]); setActiveFormTab("basic"); setIsModalOpen(true); setFoodTypePage(0); setIsSaving(true); setIsLoadingGradePricing(true); try { const [detail, pricing] = await Promise.all([ getFishTypeById(fishTypeId), getPricingByFishType(fishTypeId).catch((error) => { setGradePricingError( error instanceof Error ? error.message : "Failed to load grade pricing.", ); return []; }), ]); setFormState(toFormState(detail)); setGradePricingOptions(pricing.filter((entry) => entry.isActive)); } catch (error) { setFormError( error instanceof Error ? error.message : "Failed to load fish type details.", ); } finally { setIsSaving(false); setIsLoadingGradePricing(false); } }; const toggleAllowedFoodType = (foodTypeId: string, checked: boolean) => { setFormState((previous) => { const nextSet = new Set(previous.allowedFoodTypeIds); if (checked) { nextSet.add(foodTypeId); } else { nextSet.delete(foodTypeId); } return { ...previous, allowedFoodTypeIds: Array.from(nextSet) }; }); }; const toggleCriticalParameter = (parameter: string) => { setFormState((previous) => { const hasParameter = previous.criticalParameters.includes(parameter); return { ...previous, criticalParameters: hasParameter ? previous.criticalParameters.filter((item) => item !== parameter) : [...previous.criticalParameters, parameter], }; }); }; const updateFeedingMatrix = ( updater: (matrix: FeedingRateMatrix) => void, ) => { setFormState((previous) => { const nextMatrix = cloneFeedingRateMatrix(previous.feedingRateMatrix); updater(nextMatrix); return { ...previous, feedingRateMatrix: nextMatrix }; }); }; const addFeedingTemperature = () => { updateFeedingMatrix((matrix) => { const nextTemperature = matrix.temperatures.length > 0 ? matrix.temperatures[matrix.temperatures.length - 1] + 2 : 24; matrix.temperatures.push(nextTemperature); matrix.rates = matrix.rates.map((row) => [...row, 0]); }); }; const removeFeedingTemperature = (index: number) => { updateFeedingMatrix((matrix) => { if (matrix.temperatures.length <= 1) { return; } matrix.temperatures = matrix.temperatures.filter( (_, tempIndex) => tempIndex !== index, ); matrix.rates = matrix.rates.map((row) => row.filter((_, tempIndex) => tempIndex !== index), ); }); }; const addWeightRange = () => { updateFeedingMatrix((matrix) => { matrix.weight_ranges.push({ min: 0, max: 0 }); matrix.rates.push(new Array(matrix.temperatures.length).fill(0)); }); }; const removeWeightRange = (index: number) => { updateFeedingMatrix((matrix) => { if (matrix.weight_ranges.length <= 1) { return; } matrix.weight_ranges = matrix.weight_ranges.filter( (_, rangeIndex) => rangeIndex !== index, ); matrix.rates = matrix.rates.filter((_, rowIndex) => rowIndex !== index); }); }; // Meal frequency handlers removed const updateProteinRequirement = ( index: number, field: keyof ProteinRequirementRule, value: number | null, ) => { setFormState((previous) => ({ ...previous, proteinRequirements: previous.proteinRequirements.map( (rule, ruleIndex) => ruleIndex === index ? { ...rule, [field]: value } : rule, ), })); }; const addProteinRequirement = () => { setFormState((previous) => ({ ...previous, proteinRequirements: [ ...previous.proteinRequirements, { minWeight: 0, maxWeight: null, proteinPercentage: 30 }, ], })); }; const removeProteinRequirement = (index: number) => { setFormState((previous) => ({ ...previous, proteinRequirements: previous.proteinRequirements.length === 1 ? previous.proteinRequirements : previous.proteinRequirements.filter( (_, ruleIndex) => ruleIndex !== index, ), })); }; const addExpectedDistributionRow = () => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: [ ...previous.expectedGradeDistribution, { gradePricingId: "", percentage: 0 }, ], })); }; const removeExpectedDistributionRow = (index: number) => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: previous.expectedGradeDistribution.filter( (_, rowIndex) => rowIndex !== index, ), })); }; const updateExpectedDistributionRow = ( index: number, field: keyof ExpectedGradeDistributionEntry, value: string | number, ) => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: previous.expectedGradeDistribution.map( (row, rowIndex) => rowIndex === index ? { ...row, [field]: value } : row, ), })); }; const saveFishType = async () => { setFormError(null); const validationError = validateForm(formState); if (validationError) { setFormError(validationError); return; } const payload = toUpsertPayload(formState); setIsSaving(true); try { if (editingFishTypeId) { await updateFishType(editingFishTypeId, payload); } else { await createFishType(payload); } setIsModalOpen(false); await loadFishTypes(true); } catch (error) { setFormError( error instanceof Error ? error.message : "Failed to save fish type.", ); } finally { setIsSaving(false); } }; const runCalculators = async () => { if (!calculatorFishTypeId) { setCalculatorError("Select a fish type first."); return; } setCalculatorError(null); setIsRunningCalculator(true); try { const [feedingRate, proteinRequirement] = await Promise.all([ getFeedingRate( calculatorFishTypeId, calculatorWeight, calculatorTemperature, ), getProteinRequirement(calculatorFishTypeId, calculatorWeight), ]); setFeedingRateResult(feedingRate); setProteinRequirementResult(proteinRequirement); } catch (error) { setCalculatorError( error instanceof Error ? error.message : "Failed to run calculators.", ); } finally { setIsRunningCalculator(false); } }; const isTechnician = user.role.toLowerCase() === "technician"; return (
Fish Type Management
{currentFarmLabel}
{user.name .split(" ") .map((part) => part[0]) .join("") .toUpperCase()}
{errorMessage && ( {errorMessage} )}

Fish Species Database

Live backend integration for fish type profiles and calculators

{isTechnician && ( )}
{isLoading ? ( Loading fish types... ) : fishTypes.length === 0 ? ( No fish types found. ) : (
{fishTypes.map((fishType) => (
{fishType.name}

{fishType.scientificName}

{fishType.arabicName ? (

{fishType.arabicName}

) : null}
{fishType.isActive ? "Active" : "Inactive"}

Temp: {fishType.tempMin} - {fishType.tempMax} °C

DO: {fishType.doMin} - {fishType.doSafe} mg/L

FCR Target: {fishType.fcrMin} - {fishType.fcrMax}

Survival Rate: {fishType.survivalRate}%

{isTechnician && ( )}
))}
)} Fish Type Calculators {calculatorError ? (
{calculatorError}
) : null}
setCalculatorWeight(Number(event.target.value) || 0) } />
setCalculatorTemperature(Number(event.target.value) || 0) } />
Feeding Rate {feedingRateResult ? `${feedingRateResult.feedingRatePercentage}% body weight/day` : "Run calculator"} Protein Requirement {proteinRequirementResult ? `${proteinRequirementResult.proteinPercentage}% protein` : "Run calculator"}
{ if (!open && !isSaving) { setFormError(null); } setIsModalOpen(open); }} >
{editingFishTypeId ? "Edit Fish Type" : "Create New Fish Type"} Configure fish type profile, water quality, feeding matrix, protein rules, and food compatibility. {formError && (
{formError}
)}
setActiveFormTab(value as FormTab)} className="px-6 py-5 space-y-5" > Basic Info Water Quality Feeding Rates Protein Food Types
setFormState((previous) => ({ ...previous, name: event.target.value, })) } />
setFormState((previous) => ({ ...previous, scientificName: event.target.value, })) } />
setFormState((previous) => ({ ...previous, arabicName: event.target.value, })) } />
setFormState((previous) => ({ ...previous, targetSGR: toNumber(event.target.value), })) } />