"use client"; import { useState, useEffect } from "react"; import Tooltip from "@/components/ui/Tooltip"; import { formatDate } from "@/lib/utils"; export default function FieldWithHistory({ tableName, recordId, fieldName, currentValue, displayValue = null, label = null, className = "", }) { const [hasHistory, setHasHistory] = useState(false); const [history, setHistory] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchHistory = async () => { try { const response = await fetch( `/api/field-history?table_name=${tableName}&record_id=${recordId}&field_name=${fieldName}` ); if (response.ok) { const historyData = await response.json(); setHistory(historyData); setHasHistory(historyData.length > 0); } } catch (error) { console.error("Failed to fetch field history:", error); } finally { setLoading(false); } }; if (tableName && recordId && fieldName) { fetchHistory(); } else { setLoading(false); } }, [tableName, recordId, fieldName]); // Format value for display const getDisplayValue = (value) => { if (displayValue !== null) return displayValue; if (value && fieldName.includes("date")) { try { return formatDate(value); } catch { return value; } } return value || "N/A"; }; // Create tooltip content const tooltipContent = history.length > 0 && (
Change History:
{history.map((change, index) => (
Changed to: {getDisplayValue(change.new_value)}
{change.old_value && (
From: {getDisplayValue(change.old_value)}
)} {change.changed_by_name && (
by {change.changed_by_name}
)}
{formatDate(change.changed_at)}
{change.change_reason && (
Reason: {change.change_reason}
)}
))}
); if (loading) { return (
{label && {label}}

{getDisplayValue(currentValue)}

); } return (
{label && {label}}

{getDisplayValue(currentValue)}

{hasHistory && ( )}
); }