"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { motion, AnimatePresence } from "framer-motion"; import { Search, Plus, Filter, SlidersHorizontal, Leaf, Calendar, AlertTriangle, Loader2 } from "lucide-react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"; import { Separator } from "@/components/ui/separator"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuLabel, } from "@/components/ui/dropdown-menu"; import { Badge } from "@/components/ui/badge"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { FarmCard } from "./farm-card"; import { AddFarmForm } from "./add-farm-form"; import type { Farm } from "@/types"; import { fetchFarms } from "@/api/farm"; /** * FarmSetupPage component allows users to search, filter, sort, and add farms. */ export default function FarmSetupPage() { const router = useRouter(); // Component state const [isDialogOpen, setIsDialogOpen] = useState(false); const [searchQuery, setSearchQuery] = useState(""); const [farms, setFarms] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [activeFilter, setActiveFilter] = useState("all"); const [sortOrder, setSortOrder] = useState<"newest" | "oldest" | "alphabetical">("newest"); // Load farms when the component mounts. useEffect(() => { async function loadFarms() { try { setIsLoading(true); setError(null); const data = await fetchFarms(); setFarms(data); } catch (err) { setError(err instanceof Error ? err.message : "An unknown error occurred"); } finally { setIsLoading(false); } } loadFarms(); }, []); /** * Handles adding a new farm. * * @param data - Partial Farm data from the form. */ const handleAddFarm = async (data: Partial) => { try { // Simulate an API call delay for adding a new farm. await new Promise((resolve) => setTimeout(resolve, 800)); const newFarm: Farm = { id: Math.random().toString(36).substr(2, 9), name: data.name!, location: data.location!, type: data.type!, createdAt: new Date(), area: data.area || "0 hectares", crops: 0, }; setFarms((prev) => [newFarm, ...prev]); setIsDialogOpen(false); } catch (err) { setError("Failed to add farm. Please try again."); } }; // Filter and sort farms based on the current state. const filteredAndSortedFarms = farms .filter( (farm) => (activeFilter === "all" || farm.type === activeFilter) && (farm.name.toLowerCase().includes(searchQuery.toLowerCase()) || farm.location.toLowerCase().includes(searchQuery.toLowerCase()) || farm.type.toLowerCase().includes(searchQuery.toLowerCase())) ) .sort((a, b) => { if (sortOrder === "newest") { return b.createdAt.getTime() - a.createdAt.getTime(); } else if (sortOrder === "oldest") { return a.createdAt.getTime() - b.createdAt.getTime(); } else { return a.name.localeCompare(b.name); } }); // Get available farm types for filters. const farmTypes = ["all", ...new Set(farms.map((farm) => farm.type))]; return (
{/* Header */}

Your Farms

Manage and monitor all your agricultural properties

setSearchQuery(e.target.value)} />
{/* Filtering and sorting controls */}
{farmTypes.map((type) => ( setActiveFilter(type)}> {type === "all" ? "All Farms" : type} ))}
Sort by setSortOrder("newest")}> Newest first {sortOrder === "newest" && } setSortOrder("oldest")}> Oldest first {sortOrder === "oldest" && } setSortOrder("alphabetical")}> Alphabetical {sortOrder === "alphabetical" && }
{/* Error state */} {error && ( Error {error} )} {/* Loading state */} {isLoading && (

Loading your farms...

)} {/* Empty state */} {!isLoading && !error && filteredAndSortedFarms.length === 0 && (

No farms found

{searchQuery || activeFilter !== "all" ? (

No farms match your current filters. Try adjusting your search or filters.

) : (

You haven't added any farms yet. Get started by adding your first farm.

)}
)} {/* Grid of farm cards */} {!isLoading && !error && filteredAndSortedFarms.length > 0 && (
setIsDialogOpen(true)} /> {filteredAndSortedFarms.map((farm, index) => ( router.push(`/farms/${farm.id}`)} /> ))}
)}
{/* Add Farm Dialog */} Add New Farm Fill out the details below to add a new farm to your account. setIsDialogOpen(false)} />
); } /** * A helper component to render the Check icon. * * @param props - Optional className for custom styling. */ function Check({ className }: { className?: string }) { return ( ); }