"use client"; import React, { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { ArrowLeft, MapPin, Plus, Sprout, Calendar, LayoutGrid, AlertTriangle, Loader2, Home, ChevronRight, Droplets, Sun, Wind, } from "lucide-react"; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { CropDialog } from "./crop-dialog"; import { CropCard } from "./crop-card"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { motion, AnimatePresence } from "framer-motion"; import type { Farm, Crop } from "@/types"; import { fetchFarmDetails } from "@/api/farm"; /** * Used in Next.js; params is now a Promise and must be unwrapped with React.use() */ interface FarmDetailPageProps { params: Promise<{ farmId: string }>; } export default function FarmDetailPage({ params }: FarmDetailPageProps) { // Unwrap the promised params using React.use() (experimental) const resolvedParams = React.use(params); const router = useRouter(); const [farm, setFarm] = useState(null); const [crops, setCrops] = useState([]); const [isDialogOpen, setIsDialogOpen] = useState(false); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [activeFilter, setActiveFilter] = useState("all"); // Fetch farm details on initial render using the resolved params useEffect(() => { async function loadFarmDetails() { try { setIsLoading(true); setError(null); const { farm, crops } = await fetchFarmDetails(resolvedParams.farmId); setFarm(farm); setCrops(crops); } catch (err) { if (err instanceof Error) { if (err.message === "FARM_NOT_FOUND") { router.push("/not-found"); return; } setError(err.message); } else { setError("An unknown error occurred"); } } finally { setIsLoading(false); } } loadFarmDetails(); }, [resolvedParams.farmId, router]); /** * Handles adding a new crop. */ const handleAddCrop = async (data: Partial) => { try { // Simulate API delay await new Promise((resolve) => setTimeout(resolve, 800)); const newCrop: Crop = { id: Math.random().toString(36).substr(2, 9), farmId: farm!.id, name: data.name!, plantedDate: data.plantedDate!, status: data.status!, variety: data.variety || "Standard", area: data.area || "0 hectares", healthScore: data.status === "growing" ? 85 : 0, progress: data.status === "growing" ? 10 : 0, }; setCrops((prev) => [newCrop, ...prev]); // Update the farm's crop count if (farm) { setFarm({ ...farm, crops: farm.crops + 1 }); } setIsDialogOpen(false); } catch (err) { setError("Failed to add crop. Please try again."); } }; // Filter crops based on the active filter const filteredCrops = crops.filter((crop) => activeFilter === "all" || crop.status === activeFilter); // Calculate crop counts grouped by status const cropCounts = { all: crops.length, growing: crops.filter((crop) => crop.status === "growing").length, planned: crops.filter((crop) => crop.status === "planned").length, harvested: crops.filter((crop) => crop.status === "harvested").length, }; return (
{/* Breadcrumbs */} {/* Back button */} {/* Error state */} {error && ( Error {error} )} {/* Loading state */} {isLoading && (

Loading farm details...

)} {/* Farm details */} {!isLoading && !error && farm && ( <>
{/* Farm info card */}
{farm.type}
Created {farm.createdAt.toLocaleDateString()}

{farm.name}

{farm.location}

Total Area

{farm.area}

Total Crops

{farm.crops}

Growing Crops

{cropCounts.growing}

Harvested

{cropCounts.harvested}

{/* Weather card */} Current Conditions Weather at your farm location

Temperature

{farm.weather?.temperature}°C

Humidity

{farm.weather?.humidity}%

Sunlight

{farm.weather?.sunlight}%

Rainfall

{farm.weather?.rainfall}

{/* Crops section */}

Crops

Manage and monitor all crops in this farm

setActiveFilter("all")}> All Crops ({cropCounts.all}) setActiveFilter("growing")}> Growing ({cropCounts.growing}) setActiveFilter("planned")}> Planned ({cropCounts.planned}) setActiveFilter("harvested")}> Harvested ({cropCounts.harvested}) {filteredCrops.length === 0 ? (

No crops found

{activeFilter === "all" ? "You haven't added any crops to this farm yet." : `No ${activeFilter} crops found. Try a different filter.`}

) : (
{filteredCrops.map((crop, index) => ( router.push(`/farms/${crop.farmId}/crops/${crop.id}`)} /> ))}
)}
{/* Growing tab */} {filteredCrops.length === 0 ? (

No growing crops

You don't have any growing crops in this farm yet.

) : (
{filteredCrops.map((crop, index) => ( router.push(`/farms/${crop.farmId}/crops/${crop.id}`)} /> ))}
)}
{/* Planned tab */} {filteredCrops.length === 0 ? (

No planned crops

You don't have any planned crops in this farm yet.

) : (
{filteredCrops.map((crop, index) => ( router.push(`/farms/${crop.farmId}/crops/${crop.id}`)} /> ))}
)}
{/* Harvested tab */} {filteredCrops.length === 0 ? (

No harvested crops

You don't have any harvested crops in this farm yet.

) : (
{filteredCrops.map((crop, index) => ( router.push(`/farms/${crop.farmId}/crops/${crop.id}`)} /> ))}
)}
)}
{/* Add Crop Dialog */}
); }