import { Check, Edit2, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { Link } from "react-router-dom"; const InlineEdit = ({ value, onSave, onCancel, placeholder = "Enter value...", maxLength = 100, className = "", disabled = false, validate = null, linkTo = null, }) => { const [isEditing, setIsEditing] = useState(false); const [editValue, setEditValue] = useState(value); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(""); const inputRef = useRef(null); useEffect(() => { if (isEditing && inputRef.current) { inputRef.current.focus(); inputRef.current.select(); } }, [isEditing]); useEffect(() => { setEditValue(value); }, [value]); const handleEdit = () => { if (disabled) return; setIsEditing(true); setEditValue(value); setError(""); }; const handleCancel = () => { setIsEditing(false); setEditValue(value); setError(""); if (onCancel) onCancel(); }; const handleSave = async () => { if (disabled || isLoading) return; // Validate if validator function provided if (validate) { const validationError = validate(editValue); if (validationError) { setError(validationError); return; } } // Check if value actually changed if (editValue.trim() === value.trim()) { setIsEditing(false); return; } setIsLoading(true); setError(""); try { await onSave(editValue.trim()); setIsEditing(false); } catch (err) { setError(err.message || "Failed to save"); } finally { setIsLoading(false); } }; const handleKeyDown = (e) => { if (e.key === "Enter") { e.preventDefault(); handleSave(); } else if (e.key === "Escape") { e.preventDefault(); handleCancel(); } }; if (isEditing) { return (