import { useState, useEffect } from 'react' import { Code, Table, Plus, Trash2 } from 'lucide-react' import { useTranslation } from 'react-i18next' import { cn } from '@/lib/utils' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Textarea } from '@/components/ui/textarea' type ModelMappingEditorProps = { value: string onChange: (value: string) => void disabled?: boolean } type MappingRow = { id: string from: string to: string } export function ModelMappingEditor({ value, onChange, disabled = false, }: ModelMappingEditorProps) { const { t } = useTranslation() const [mode, setMode] = useState<'visual' | 'json'>('visual') const [rows, setRows] = useState([]) const [jsonValue, setJsonValue] = useState(value) const parseJsonToRows = (json: string) => { try { if (!json.trim()) { setRows([]) return } const parsed = JSON.parse(json) const newRows: MappingRow[] = Object.entries(parsed).map( ([from, to], index) => ({ id: `${Date.now()}-${index}`, from, to: String(to), }) ) setRows(newRows) } catch (_error) { // Invalid JSON, keep current rows } } // Parse JSON to rows when value changes externally useEffect(() => { // eslint-disable-next-line react-hooks/set-state-in-effect setJsonValue(value) parseJsonToRows(value) }, [value]) const convertRowsToJson = (updatedRows: MappingRow[]): string => { if (updatedRows.length === 0) { return '' } const obj: Record = {} updatedRows.forEach((row) => { if (row.from.trim()) { obj[row.from.trim()] = row.to.trim() } }) return JSON.stringify(obj, null, 2) } const handleAddRow = () => { const newRow: MappingRow = { id: `${Date.now()}`, from: '', to: '', } const updatedRows = [...rows, newRow] setRows(updatedRows) } const handleDeleteRow = (id: string) => { const updatedRows = rows.filter((row) => row.id !== id) setRows(updatedRows) const json = convertRowsToJson(updatedRows) setJsonValue(json) onChange(json) } const handleRowChange = ( id: string, field: 'from' | 'to', newValue: string ) => { const updatedRows = rows.map((row) => row.id === id ? { ...row, [field]: newValue } : row ) setRows(updatedRows) const json = convertRowsToJson(updatedRows) setJsonValue(json) onChange(json) } const handleJsonChange = (newJson: string) => { setJsonValue(newJson) onChange(newJson) parseJsonToRows(newJson) } const handleFillTemplate = () => { const template = JSON.stringify( { 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125' }, null, 2 ) setJsonValue(template) onChange(template) parseJsonToRows(template) } const toggleMode = () => { if (mode === 'visual') { // Switching to JSON mode: sync rows to JSON const json = convertRowsToJson(rows) setJsonValue(json) onChange(json) setMode('json') } else { // Switching to visual mode: sync JSON to rows parseJsonToRows(jsonValue) setMode('visual') } } return (