import { useState, useMemo, useCallback, useEffect } from 'react'; import { Kpi, Alert, CoopZone, EnvironmentData, PopulationDataPoint, LiveCount, FeedSackLogEntry, ManualFeedSackEntry, BehaviorMetrics, BehaviorDataPoint, BehaviorAnomaly, WeightStatistics, WeightDataPoint, WeightDistributionPoint, WeightAlert, NetworkDevice, BandwidthHistoryPoint, BatchService, BatchJob, CycleData, MultiCoopChartPoint, MultiCoopWeightSummary, FeedWastageStats, WastageHotspot, FeedWastageAlert, WastageDataPoint, FeedScheduleRecommendation, FeedingEvent, ConsumptionPatternPoint, ScheduleInfluencingFactors, ErpSyncStats, ErpEndpoint, VetVisit, OcrDocument, ManualWeighingRecord, AiRecommendation, RecommendationStatus, CkaleWeightPoint, MultiCoopWeightData, FcrDataPoint, WeightDistributionStats, SensorWeightSummary, } from '../../types.ts'; import { apiClient } from '../../services/apiService.ts'; import { cycleData as initialCycles, defaultPhases } from '../../mockData/cycleData.ts'; export const useStaticDataStore = () => { const [kpis, setKpis] = useState>({}); const [alerts, setAlerts] = useState([]); const [coopZones, _setCoopZones] = useState([]); const [environmentData, setEnvironmentData] = useState([]); const [populationHistory, _setPopulationHistory] = useState([]); const [liveCounts, setLiveCounts] = useState([]); const [feedSackHistory, setFeedSackHistory] = useState([]); const [availableFeedSackCameras, setAvailableFeedSackCameras] = useState([]); const [manualFeedSackEntries, setManualFeedSackEntries] = useState([]); const [behaviorMetrics, _setBehaviorMetrics] = useState({ activityIndex: 0, stressLevel: { value: 0, status: 'ok' }, eatingPattern: { value: 0, status: 'ok' }, drinkingPattern: { value: 0, status: 'ok' }, }); const [behaviorHistory, _setBehaviorHistory] = useState([]); const [behaviorAnomalies, _setBehaviorAnomalies] = useState([]); const [initialWeight, setInitialWeight] = useState({ averageWeight: { value: 0, unit: 'g', status: 'ok' }, avgDailyGain: { value: 0, unit: 'g/hari', status: 'ok' }, uniformity: { value: 0, unit: '%', status: 'ok' }, }); const [weightHistory, setWeightHistory] = useState([]); const [weightDistribution, setWeightDistribution] = useState([]); const [weightAlerts, setWeightAlerts] = useState([]); const [networkDevices, _setNetworkDevices] = useState([]); const [bandwidthHistory, _setBandwidthHistory] = useState([]); const [batchServices, _setBatchServices] = useState([]); const [batchJobs, _setBatchJobs] = useState([]); const [cycles, setCycles] = useState(initialCycles); const [feedWastageStats, _setFeedWastageStats] = useState({ currentWastage: { value: 0, unit: '%', status: 'ok' }, totalWastedKg: { value: 0, unit: 'kg' }, estimatedLoss: { value: 0, unit: 'Rp' }, criticalZones: { value: 0, unit: 'zona' }, }); const [wastageHotspots, _setWastageHotspots] = useState([]); const [wastageAlerts, _setWastageAlerts] = useState([]); const [wastageHistory, _setWastageHistory] = useState([]); const [feedSchedule, _setFeedSchedule] = useState({ nextFeedingTime: new Date(), lastFeedingTime: new Date(), reason: '', }); const [feedingEvents, setFeedingEvents] = useState([]); const [consumptionPattern, _setConsumptionPattern] = useState([]); const [scheduleFactors, _setScheduleFactors] = useState({ temperature: { value: 0, unit: '°C', status: 'ok' }, humidity: { value: 0, unit: '%', status: 'ok' }, activityLevel: { value: 0, unit: '%', status: 'ok' }, }); const [erpSyncStats, _setErpSyncStats] = useState({ status: 'Maintenance', recordsSyncedToday: 0, lastSync: new Date(), }); const [erpEndpoints, _setErpEndpoints] = useState([]); const [vetVisits, setVetVisits] = useState([]); const [ocrDocuments, setOcrDocuments] = useState([]); const [manualWeighingData, setManualWeighingData] = useState([]); const [ckaleData, setCkaleData] = useState([]); const [aiRecommendations, setAiRecommendations] = useState([]); const [multiCoopWeightData, setMultiCoopWeightData] = useState<{ target: { day: number; weight: number }[]; coops: MultiCoopWeightData[]; }>({ target: [], coops: [] }); const [fcrComparisonData, setFcrComparisonData] = useState([]); // Weight distribution date selection state - Initialize with yesterday's date const getYesterday = () => { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); return yesterday; }; const [distributionSelectedDate, setDistributionSelectedDate] = useState(getYesterday()); const [distributionStats, setDistributionStats] = useState(null); const [sensorWeightSummary, setSensorWeightSummary] = useState([]); // New scale data states for revamped dashboard const [dailyWeightData, setDailyWeightData] = useState([]); // DailyWeightPoint[] const [dailyWeightGainData, setDailyWeightGainData] = useState([]); // DailyWeightGainPoint[] const [deviceWeightData, setDeviceWeightData] = useState([]); // DeviceWeightData[] const [scaleDataLoading, setScaleDataLoading] = useState(true); // Start as true to prevent flash const [scaleDataLastUpdate, setScaleDataLastUpdate] = useState(new Date()); const [dailyDataLoading, setDailyDataLoading] = useState(false); // Loading state for daily data section // Load cycles from database on mount useEffect(() => { const loadCycles = async () => { try { const dbCycles = await apiClient.getCycles(); // Transform database format to CycleData format const transformedCycles: CycleData[] = dbCycles.map((cycle: any) => ({ id: cycle.id, totalDays: cycle.totalDays, currentDay: cycle.currentDay, startDate: new Date(cycle.startDate), endDate: cycle.endDate ? new Date(cycle.endDate) : undefined, chickInWeight: cycle.chickInWeight, docInCount: cycle.docInCount, phases: defaultPhases, status: cycle.status, })); setCycles(transformedCycles); } catch (error) { console.error('Failed to load cycles from database:', error); // Keep using initial mock data as fallback } }; loadCycles(); }, []); const coopNamesForChart = useMemo(() => { if (!multiCoopWeightData || !multiCoopWeightData.coops) return []; return ['Target', ...multiCoopWeightData.coops.map((d) => d.coopName)]; }, [multiCoopWeightData]); const multiCoopChartData = useMemo(() => { if (!multiCoopWeightData || !multiCoopWeightData.target || !multiCoopWeightData.coops) return []; const chartPoints: { [day: number]: MultiCoopChartPoint } = {}; const allData = [ { coopName: 'Target', history: multiCoopWeightData.target }, ...multiCoopWeightData.coops, ]; allData.forEach((coop) => { coop.history.forEach((point) => { const chartPoint = chartPoints[point.day] ?? (chartPoints[point.day] = { day: point.day }); chartPoint[coop.coopName] = point.weight; }); }); return Object.values(chartPoints).sort((a, b) => a.day - b.day); }, [multiCoopWeightData]); const multiCoopSummaryData = useMemo(() => { if (!multiCoopWeightData || !multiCoopWeightData.coops || !multiCoopWeightData.target) return []; return multiCoopWeightData.coops.map((coop) => { const history = coop.history; if (history.length < 2) { const currentWeight = history[0]?.weight || 0; return { coopId: coop.coopId, coopName: coop.coopName, currentWeight, adg: 0, uniformity: 0, deviation: 0, }; } const currentWeight = history[history.length - 1]?.weight ?? 0; const previousWeight = history[history.length - 2]?.weight ?? 0; const adg = currentWeight - previousWeight; const targetWeightForDay = multiCoopWeightData.target.find((t) => t.day === history[history.length - 1]?.day) ?.weight || currentWeight; const deviation = currentWeight - targetWeightForDay; // Mock uniformity const uniformity = 80 + deviation / 10 + (Math.random() - 0.5) * 5; return { coopId: coop.coopId, coopName: coop.coopName, currentWeight, adg: Math.round(adg), uniformity: Math.round(uniformity), deviation: Math.round(deviation), }; }); }, [multiCoopWeightData]); const onUpdateVetVisit = useCallback((updatedVisit: VetVisit) => { setVetVisits((prev) => prev.map((v) => (v.id === updatedVisit.id ? updatedVisit : v))); }, []); const onAddVetVisit = useCallback((visitData: Omit) => { const newVisit: VetVisit = { ...visitData, id: `vet-${Date.now()}`, status: 'Scheduled', }; setVetVisits((prev) => [...prev, newVisit]); }, []); const onUpdateOcrDocument = useCallback((updatedDocument: OcrDocument) => { setOcrDocuments((prev) => prev.map((d) => (d.id === updatedDocument.id ? updatedDocument : d))); }, []); const onAddFeedingEvent = useCallback((eventData: Omit) => { const newEvent: FeedingEvent = { ...eventData, id: `event-${Date.now()}`, status: eventData.time > new Date() ? 'upcoming' : 'completed', }; setFeedingEvents((prev) => [...prev, newEvent]); }, []); const onUpdateFeedingEvent = useCallback((updatedEvent: FeedingEvent) => { setFeedingEvents((prev) => prev.map((e) => (e.id === updatedEvent.id ? updatedEvent : e))); }, []); const onUpdateManualWeighingRecord = useCallback((updatedRecord: ManualWeighingRecord) => { setManualWeighingData((prev) => prev.map((r) => (r.date === updatedRecord.date ? updatedRecord : r)) ); }, []); const onUpdateRecommendationStatus = useCallback((id: string, status: RecommendationStatus) => { setAiRecommendations((prev) => prev.map((rec) => (rec.id === id ? { ...rec, status } : rec))); }, []); const onUpdateCycleDates = useCallback( async ( cycleId: string, startDate: Date, endDate: Date, chickInWeight?: number, docInCount?: number ) => { // Update local state first for immediate UI feedback setCycles((prev) => prev.map((cycle) => { if (cycle.id === cycleId) { const totalDays = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1; return { ...cycle, startDate, totalDays, endDate, chickInWeight, docInCount }; } return cycle; }) ); // Persist to database try { const totalDays = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1; const cycle = await apiClient.getCycleById(cycleId); await apiClient.updateCycle(cycleId, { totalDays, currentDay: cycle.currentDay, startDate: startDate.toISOString().split('T')[0] ?? '', endDate: endDate.toISOString().split('T')[0] ?? '', chickInWeight: chickInWeight || null, docInCount: docInCount || null, status: cycle.status, }); } catch (error) { console.error('Failed to update cycle in database:', error); // Could add error handling/rollback here } }, [] ); const onCreateCycle = useCallback( async (startDate: Date, docInCount?: number, chickInWeight?: number) => { const year = startDate.getFullYear(); const month = String(startDate.getMonth() + 1).padStart(2, '0'); const day = String(startDate.getDate()).padStart(2, '0'); const newId = `CYCLE-JBW-${year}-${month}-${day}`; const totalDays = 42; const endDate = new Date(startDate); endDate.setDate(endDate.getDate() + totalDays - 1); const today = new Date(); today.setHours(0, 0, 0, 0); const startMs = new Date(startDate).setHours(0, 0, 0, 0); const diffMs = today.getTime() - startMs; const currentDay = diffMs >= 0 ? Math.min(Math.floor(diffMs / (1000 * 60 * 60 * 24)) + 1, totalDays) : 0; const newCycle: CycleData = { id: newId, totalDays, currentDay, startDate, endDate, chickInWeight, docInCount, phases: defaultPhases, status: 'Active', }; // Optimistic UI update: mark previous active as Completed, add new cycle setCycles((prev) => { const updated = prev.map((c) => c.status === 'Active' ? { ...c, status: 'Completed' as const, currentDay: c.totalDays } : c ); return [...updated, newCycle]; }); // Persist to database // NOTE: Backend automatically marks previous active cycles as Completed when creating a new Active cycle try { await apiClient.createCycle({ id: newId, totalDays, currentDay, startDate: startDate.toISOString().split('T')[0] ?? '', endDate: endDate.toISOString().split('T')[0] ?? '', chickInWeight: chickInWeight || null, docInCount: docInCount || null, status: 'Active', }); } catch (error) { console.error('Failed to create cycle in database:', error); // Rollback optimistic update on error setCycles((prev) => prev.filter((c) => c.id !== newId)); } }, [cycles] ); // Fetch manual feed sack data by date range const fetchManualFeedSackData = useCallback(async (startDate: string, endDate: string) => { try { const entries = await apiClient.getManualFeedSackEntries(startDate, endDate); setManualFeedSackEntries(entries); } catch (error) { console.error('Failed to fetch manual feed sack entries:', error); setManualFeedSackEntries([]); } }, []); return { kpis, alerts, coopZones, environmentData, populationHistory, liveCounts, feedSackHistory, availableFeedSackCameras, manualFeedSackEntries, behaviorMetrics, behaviorHistory, behaviorAnomalies, initialWeight, weightHistory, weightDistribution, weightAlerts, networkDevices, bandwidthHistory, batchServices, batchJobs, cycles, feedWastageStats, wastageHotspots, wastageAlerts, wastageHistory, feedSchedule, feedingEvents, consumptionPattern, scheduleFactors, multiCoopChartData, multiCoopSummaryData, coopNamesForChart, erpSyncStats, erpEndpoints, vetVisits, ocrDocuments, manualWeighingData, aiRecommendations, ckaleData, fcrComparisonData, // Weight distribution date selection state distributionSelectedDate, distributionStats, sensorWeightSummary, // New scale data for revamped dashboard dailyWeightData, dailyWeightGainData, deviceWeightData, scaleDataLoading, scaleDataLastUpdate, dailyDataLoading, setMultiCoopWeightData, // Expose setters needed for LIVE API integration on the weight dashboard setInitialWeight, setWeightHistory, setWeightDistribution, setWeightAlerts, setFcrComparisonData, setCkaleData, // Weight distribution date selection setters setDistributionSelectedDate, setDistributionStats, setSensorWeightSummary, // New scale data setters setDailyWeightData, setDailyWeightGainData, setDeviceWeightData, setScaleDataLoading, setScaleDataLastUpdate, setDailyDataLoading, // Expose setters for IoT, feed sack, and other API integrations setEnvironmentData, setFeedSackHistory, setAvailableFeedSackCameras, setManualFeedSackEntries, fetchManualFeedSackData, setAlerts, setKpis, setFeedingEvents, setVetVisits, setLiveCounts, onUpdateVetVisit, onUpdateOcrDocument, onAddFeedingEvent, onUpdateFeedingEvent, onAddVetVisit, onUpdateManualWeighingRecord, onUpdateRecommendationStatus, onUpdateCycleDates, onCreateCycle, }; };