import { useState, useEffect, useRef } from "react"; import PropTypes from "prop-types"; import { saveProfile, deleteProfile } from "../../api/api"; import Modal from "../ui/Modal"; function unsanitize(text) { return text.replace(/\\:/g, ":").replace(/\\n/g, "\n"); } function ProfileModal({ profile = null, isOpen, onClose, onSave }) { const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [tags, setTags] = useState([]); const [newTag, setNewTag] = useState(""); const [error, setError] = useState(""); const initialProfileRef = useRef(profile); useEffect(() => { if (isOpen) { if (profile && profile.id !== 0) { initialProfileRef.current = profile; setName(unsanitize(profile.name)); setDescription(unsanitize(profile.description)); setTags(profile.tags ? profile.tags.map(unsanitize) : []); } else { initialProfileRef.current = null; setName(profile ? unsanitize(profile.name) : ""); setDescription(profile ? unsanitize(profile.description) : ""); setTags(profile ? profile.tags.map(unsanitize) : []); } setError(""); setNewTag(""); } }, [profile, isOpen]); const handleSave = async () => { if (!name.trim()) { setError("Name is required."); return; } try { await saveProfile({ id: profile ? profile.id : 0, name, description, tags, }); onSave(); onClose(); } catch (error) { console.error("Error saving profile:", error); setError("Failed to save profile. Please try again."); } }; const handleDelete = async () => { const confirmDeletion = window.confirm( "Are you sure you want to delete this profile?" ); if (!confirmDeletion) return; try { await deleteProfile(profile.id); onSave(); onClose(); } catch (error) { console.error("Error deleting profile:", error); setError("Failed to delete profile. Please try again."); } }; const handleAddTag = () => { if (newTag.trim() && !tags.includes(newTag.trim())) { setTags([...tags, newTag.trim()]); setNewTag(""); } }; const handleRemoveTag = (tagToRemove) => { setTags(tags.filter((tag) => tag !== tagToRemove)); }; return ( {error &&
{error}
}
setName(e.target.value)} placeholder="Enter profile name" className="w-full p-2 border rounded dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600" />