"use client"; import { useEffect, useState } from "react"; import { fetchPurchaseOrders } from "../lib/api"; import { PurchaseOrder } from "../lib/types"; import BrandLoader from "./BrandLoader"; export default function MarketMonitor() { const [ocs, setOcs] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [filter, setFilter] = useState("todos"); const [page, setPage] = useState(1); const itemsPerPage = 50; useEffect(() => { loadOcs(); setPage(1); // Reset page on filter change }, [filter]); async function loadOcs() { setIsLoading(true); setError(null); try { const data = await fetchPurchaseOrders(undefined, filter); if (!data || data.length === 0) { setError("No purchase orders found for today. Try again later or check your API connection."); setOcs([]); } else { // Sort by code descending (usually higher codes are newer) const sorted = [...data].sort((a, b) => b.code.localeCompare(a.code)); setOcs(sorted); } } catch (e) { const errorMsg = e instanceof Error ? e.message : "Failed to load purchase orders. Check your backend connection."; console.error("OC Load Error:", e); setError(errorMsg); setOcs([]); } finally { setIsLoading(false); } } const formatCurrency = (amount: number | null, currency: string | null) => { if (!amount || amount === 0) return Pending...; return new Intl.NumberFormat("es-CL", { style: "currency", currency: currency || "CLP", maximumFractionDigits: 0 }).format(amount); }; const paginatedOcs = ocs.slice((page - 1) * itemsPerPage, page * itemsPerPage); const totalPages = Math.ceil(ocs.length / itemsPerPage); return (

Real-Time Intelligence

Market Monitor

Monitoring {ocs.length.toLocaleString()} active orders from today.

{["todos", "aceptada", "enviadaproveedor"].map((f) => ( ))}
{isLoading ? (
) : error ? (
⚠️

Connection Error

{error}

Troubleshoot
) : ocs.length > 0 ? ( <>
{paginatedOcs.map((oc) => ( ))}
Order ID / Description Buyer Vendor Total
{oc.code}
{oc.name || "Orden de Compra"}
{oc.buyer}
{oc.buyer !== "Unknown" ? oc.buyer : ...}
{oc.provider !== "Unknown" ? oc.provider : ...}
{formatCurrency(oc.total_amount, oc.currency)}
{/* Pagination Controls */}
Showing {((page - 1) * itemsPerPage) + 1} to {Math.min(page * itemsPerPage, ocs.length)} of {ocs.length}
) : (
🛒

No purchase orders detected in the last hour.

)}
); }