"use client"; import { useState, useEffect } from "react"; import Tooltip from "@/components/ui/Tooltip"; import { formatDate } from "@/lib/utils"; import { useTranslation } from "@/lib/i18n"; import { formatDistanceToNow } from "date-fns"; import { pl, enUS } from "date-fns/locale"; export default function FieldWithHistory({ tableName, recordId, fieldName, currentValue, displayValue = null, label = null, className = "", }) { const { t, language } = useTranslation(); const [hasHistory, setHasHistory] = useState(false); const [history, setHistory] = useState([]); const [loading, setLoading] = useState(true); // Get locale for date-fns const locale = language === 'pl' ? pl : enUS; 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 || t("common.na"); }; // Create tooltip content const tooltipContent = history.length > 0 && (
{t("common.changeHistory")} ({history.length})
{history.map((change, index) => (
{/* New Value */}
{t("common.changedTo")} {getDisplayValue(change.new_value)}
{/* Old Value */} {change.old_value && (
{t("common.from")} {getDisplayValue(change.old_value)}
)} {/* Changed By */} {change.changed_by_name && (
{t("common.by")} {change.changed_by_name}
)}
{/* Timestamp */}
{formatDistanceToNow(new Date(change.changed_at), { addSuffix: true, locale: locale })}
{formatDate(change.changed_at)}
{/* Change Reason */} {change.change_reason && (
{t("common.reason")} {change.change_reason}
)}
))}
); if (loading) { return (
{label && {label}}

{getDisplayValue(currentValue)}

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

{getDisplayValue(currentValue)}

{hasHistory && (
{/* History Icon with Badge */}
{history.length}
)}
); }