"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 && (
{getDisplayValue(currentValue)}
{getDisplayValue(currentValue)}
{hasHistory && (