import { useState, useMemo } from 'react'; import { Link2, AlertCircle, X } from 'lucide-react'; import { Button, TypeBadge, Popover, PopoverContent, PopoverTrigger, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, ConvertedValue, DataGrid, } from '@/components'; import { useTables } from '@/features/database/hooks/useTables'; import { useRecords } from '@/features/database/hooks/useRecords'; import { convertSchemaToColumns } from '@/features/database/components/DatabaseDataGrid'; import { formatValueForDisplay } from '@/lib/utils/utils'; interface ForeignKeyCellProps { value: string; foreignKey: { table: string; column: string; }; onJumpToTable?: (tableName: string) => void; } export function ForeignKeyCell({ value, foreignKey, onJumpToTable }: ForeignKeyCellProps) { const [open, setOpen] = useState(false); const { useTableSchema } = useTables(); const recordsHook = useRecords(foreignKey.table); // Helper function to safely render any value type (including JSON objects) const renderValue = (val: ConvertedValue): string => { return formatValueForDisplay(val); }; // Fetch the referenced record when popover opens const searchValue = value ? renderValue(value) : ''; const { data: recordData, isLoading: _isLoading, error, } = recordsHook.useRecordByForeignKey(foreignKey.column, searchValue, open && !!value); const record = recordData; // Fetch schema for the referenced table const { data: schema } = useTableSchema(foreignKey.table, open && !!value); // Convert schema to columns for the mini DataGrid const columns = useMemo(() => { if (!schema) { return []; } // Use convertSchemaToColumns but disable foreign keys to prevent nested popovers return convertSchemaToColumns(schema, undefined, undefined).map((col) => ({ ...col, width: 200, minWidth: 200, resizable: false, editable: false, })); }, [schema]); if (!value) { return null; } const displayValue = renderValue(value); return (