'use client'; import { useState, useTransition } from 'react'; import type { InventoryConsumption } from '../../features/inventory/types'; type Props = { id: number; }; function formatDateTime(value: string) { return new Date(value).toLocaleString('sv-SE'); } export default function InventoryConsumptionHistory({ id }: Props) { const [isOpen, setIsOpen] = useState(false); const [isPending, startTransition] = useTransition(); const [error, setError] = useState(null); const [history, setHistory] = useState(null); const loadHistory = () => { setError(null); startTransition(async () => { try { const res = await fetch(`/api/inventory-history-proxy?id=${id}`, { method: 'GET', cache: 'no-store', }); if (!res.ok) { const text = await res.text(); throw new Error(text || 'Kunde inte hämta historik.'); } const data: InventoryConsumption[] = await res.json(); setHistory(data); setIsOpen(true); } catch (err) { setError(err instanceof Error ? err.message : 'Okänt fel'); } }); }; if (!isOpen) { return (
{error ?

{error}

: null}
); } return (
Förbrukningshistorik
{history && history.length > 0 ? (
{history.map((entry) => (
Använt: {entry.amountUsed}
Tid: {formatDateTime(entry.createdAt)}
{entry.comment ? (
Kommentar: {entry.comment}
) : null}
))}
) : (

Ingen förbrukningshistorik ännu.

)} {error ?

{error}

: null}
); }