"use client"; import { useState, useEffect } from "react"; import { useSearchParams } from "next/navigation"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, Cell, } from "recharts"; import { ArrowUpRight, ArrowDownRight, TrendingUp, Calendar, MapPin, RefreshCw, AlertCircle, ChevronRight, Leaf, BarChart3, LineChartIcon, PieChart, } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Progress } from "@/components/ui/progress"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Separator } from "@/components/ui/separator"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; // Define types for market data interface ITrend { direction: "up" | "down"; value: string; } interface IMarketPrice { market: string; price: number; demand: number; trend: ITrend; } export interface IMarketData { id: string; name: string; marketPrices: IMarketPrice[]; averagePrice: number; recommendedPrice: number; demandScore: number; opportunity: boolean; } export interface IHistoricalData { date: string; price: number; volume: number; } export interface IMarketComparison { name: string; price: number; demand: number; } // Types for tooltip props from recharts interface CustomTooltipProps { active?: boolean; payload?: { value: number }[]; label?: string; } // Types for MarketOpportunity props interface MarketOpportunityProps { crop: string; data: IMarketComparison[]; } // Mock data for market prices const generateMarketData = (): IMarketData[] => { const crops = ["Corn", "Wheat", "Soybeans", "Rice", "Potatoes", "Tomatoes", "Apples", "Oranges"]; const markets = ["National Market", "Regional Hub", "Local Market", "Export Market", "Wholesale Market"]; const getRandomPrice = (base: number) => Number((base + Math.random() * 2).toFixed(2)); const getRandomDemand = () => Math.floor(Math.random() * 100); const getRandomTrend = (): ITrend => Math.random() > 0.5 ? { direction: "up", value: (Math.random() * 5).toFixed(1) } : { direction: "down", value: (Math.random() * 5).toFixed(1) }; return crops.map((crop) => { const basePrice = crop === "Corn" ? 4 : crop === "Wheat" ? 6 : crop === "Soybeans" ? 10 : crop === "Rice" ? 12 : crop === "Potatoes" ? 3 : crop === "Tomatoes" ? 2 : crop === "Apples" ? 1.5 : 8; return { id: crypto.randomUUID(), name: crop, marketPrices: markets.map((market) => ({ market, price: getRandomPrice(basePrice), demand: getRandomDemand(), trend: getRandomTrend(), })), averagePrice: getRandomPrice(basePrice - 0.5), recommendedPrice: getRandomPrice(basePrice + 0.2), demandScore: getRandomDemand(), opportunity: Math.random() > 0.7, }; }); }; // Generate historical price data for a specific crop const generateHistoricalData = (crop: string, days = 30): IHistoricalData[] => { const basePrice = crop === "Corn" ? 4 : crop === "Wheat" ? 6 : crop === "Soybeans" ? 10 : crop === "Rice" ? 12 : crop === "Potatoes" ? 3 : crop === "Tomatoes" ? 2 : crop === "Apples" ? 1.5 : 8; const data: IHistoricalData[] = []; let currentPrice = basePrice; for (let i = days; i >= 0; i--) { const date = new Date(); date.setDate(date.getDate() - i); const change = (Math.random() - 0.5) * 0.4; currentPrice = Math.max(0.5, currentPrice + change); data.push({ date: date.toISOString().split("T")[0], price: Number(currentPrice.toFixed(2)), volume: Math.floor(Math.random() * 1000) + 200, }); } return data; }; // Generate market comparison data const generateMarketComparisonData = (crop: string): IMarketComparison[] => { const markets = ["National Market", "Regional Hub", "Local Market", "Export Market", "Wholesale Market"]; const basePrice = crop === "Corn" ? 4 : crop === "Wheat" ? 6 : crop === "Soybeans" ? 10 : crop === "Rice" ? 12 : crop === "Potatoes" ? 3 : crop === "Tomatoes" ? 2 : crop === "Apples" ? 1.5 : 8; return markets.map((market) => ({ name: market, price: Number((basePrice + (Math.random() - 0.5) * 2).toFixed(2)), demand: Math.floor(Math.random() * 100), })); }; // Custom tooltip for the price chart const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => { if (active && payload && payload.length) { return (

{label}

Price: ${payload[0].value}

{payload[1] &&

Volume: {payload[1].value} units

}
); } return null; }; // Market opportunity component const MarketOpportunity = ({ crop, data }: MarketOpportunityProps) => { const highestPrice = Math.max(...data.map((item) => item.price)); const bestMarket = data.find((item) => item.price === highestPrice); const highestDemand = Math.max(...data.map((item) => item.demand)); const highDemandMarket = data.find((item) => item.demand === highestDemand); return ( Sales Opportunity for {crop} Based on current market conditions

Best Price Opportunity

${bestMarket?.price}

{bestMarket?.name}

{Math.round((bestMarket!.price / (highestPrice - 1)) * 100)}% above average

Highest Demand

{highDemandMarket?.name}

{highDemandMarket?.demand}% demand
Recommendation Consider selling your {crop} at {bestMarket?.name} within the next 7 days to maximize profit.
); }; export default function MarketplacePage() { const searchParams = useSearchParams(); const initialCrop = searchParams.get("crop") || "Corn"; const [selectedCrop, setSelectedCrop] = useState(initialCrop); const [timeRange, setTimeRange] = useState("30"); const [isLoading, setIsLoading] = useState(true); const [marketData, setMarketData] = useState([]); const [historicalData, setHistoricalData] = useState([]); const [marketComparison, setMarketComparison] = useState([]); const [lastUpdated, setLastUpdated] = useState(new Date()); useEffect(() => { setIsLoading(true); const timer = setTimeout(() => { setMarketData(generateMarketData()); setHistoricalData(generateHistoricalData(selectedCrop, Number.parseInt(timeRange))); setMarketComparison(generateMarketComparisonData(selectedCrop)); setLastUpdated(new Date()); setIsLoading(false); }, 1200); return () => clearTimeout(timer); }, [selectedCrop, timeRange]); const handleRefresh = () => { setIsLoading(true); setTimeout(() => { setMarketData(generateMarketData()); setHistoricalData(generateHistoricalData(selectedCrop, Number.parseInt(timeRange))); setMarketComparison(generateMarketComparisonData(selectedCrop)); setLastUpdated(new Date()); setIsLoading(false); }, 1000); }; // Removed unused variable "selectedCropData" const getTrendColor = (trend: ITrend) => { return trend.direction === "up" ? "text-green-600" : "text-red-600"; }; const getTrendIcon = (trend: ITrend) => { return trend.direction === "up" ? ( ) : ( ); }; return (

Marketplace Information

Make informed decisions with real-time market data and price analytics

Last updated: {lastUpdated.toLocaleTimeString()}
Price Analytics Track price trends and market movements
{isLoading ? (

Loading market data...

) : ( Price Trend Market Comparison Demand Analysis
{ const date = new Date(value); return `${date.getMonth() + 1}/${date.getDate()}`; }} /> `$${value}`} domain={["dataMin - 0.5", "dataMax + 0.5"]} /> } />

Current Price

${historicalData[historicalData.length - 1]?.price.toFixed(2)}

30-Day Average

$ {( historicalData.reduce((sum, item) => sum + item.price, 0) / historicalData.length ).toFixed(2)}

Recommended Price

${(historicalData[historicalData.length - 1]?.price * 1.05).toFixed(2)}

+5% margin
`$${value}`} /> {marketComparison.map((entry, index) => ( item.price)) ? "#15803d" : "#16a34a" } /> ))}
Market comparison for {selectedCrop} as of {new Date().toLocaleDateString()} Market Price Demand Price Difference Action {marketComparison.map((market) => { const avgPrice = marketComparison.reduce((sum, m) => sum + m.price, 0) / marketComparison.length; const priceDiff = (((market.price - avgPrice) / avgPrice) * 100).toFixed(1); const isPriceHigh = Number.parseFloat(priceDiff) > 0; return ( setSelectedCrop(market.name)}> {market.name} ${market.price.toFixed(2)}
{market.demand}%
{isPriceHigh ? ( ) : ( )} {priceDiff}%
); })}
Demand Forecast Projected demand for {selectedCrop} over the next 30 days
{marketComparison.map((market) => (
{market.name} {market.demand}%
))}
)}
Market Summary Today's market overview {isLoading ? (
) : (
{marketData.slice(0, 5).map((crop) => (

{crop.name}

${crop.averagePrice.toFixed(2)} {crop.marketPrices[0].trend.direction === "up" ? ( {crop.marketPrices[0].trend.value}% ) : ( {crop.marketPrices[0].trend.value}% )}
))}
)}
Top Opportunities Best selling opportunities today {isLoading ? (
) : (
{marketData .filter((crop) => crop.opportunity) .slice(0, 3) .map((crop) => { const bestMarket = crop.marketPrices.reduce( (best, current) => (current.price > best.price ? current : best), crop.marketPrices[0] ); return (

{crop.name}

{bestMarket.market} - ${bestMarket.price.toFixed(2)}

High Demand
Recommended
); })}
)}
Market Price Table Comprehensive price data across all markets and crops {isLoading ? (
) : (
Crop {marketData[0]?.marketPrices.map((market) => ( {market.market} ))} Average Recommended {marketData.map((crop) => ( setSelectedCrop(crop.name)}> {crop.name} {crop.marketPrices.map((market) => (
${market.price.toFixed(2)} {getTrendIcon(market.trend)}
))} ${crop.averagePrice.toFixed(2)} ${crop.recommendedPrice.toFixed(2)}
))}
)}
); }