import React, { useState, useEffect, useCallback } from 'react'; import axios from 'axios'; import { useRouter } from 'next/router'; import { useToast } from '@/hooks/useToast'; import { useSession } from 'next-auth/react'; import { useNDKContext } from '@/context/NDKContext'; import { useEncryptContent } from '@/hooks/encryption/useEncryptContent'; import GenericButton from '@/components/buttons/GenericButton'; import { NDKEvent } from '@nostr-dev-kit/ndk'; import { validateEvent } from '@/utils/nostr'; import { InputText } from 'primereact/inputtext'; import { InputTextarea } from 'primereact/inputtextarea'; import { InputNumber } from 'primereact/inputnumber'; import { InputSwitch } from 'primereact/inputswitch'; import { Tooltip } from 'primereact/tooltip'; import dynamic from 'next/dynamic'; const MDEditor = dynamic(() => import("@uiw/react-md-editor"), { ssr: false }); const EditPublishedDocumentForm = ({ event }) => { const router = useRouter(); const { data: session } = useSession(); const { showToast } = useToast(); const { ndk, addSigner } = useNDKContext(); const { encryptContent } = useEncryptContent(); const [user, setUser] = useState(null); const [title, setTitle] = useState(event.title); const [summary, setSummary] = useState(event.summary); const [price, setPrice] = useState(event.price); const [isPaidResource, setIsPaidResource] = useState(event.price ? true : false); const [content, setContent] = useState(event.content); const [coverImage, setCoverImage] = useState(event.image); const [additionalLinks, setAdditionalLinks] = useState(event.additionalLinks); const [topics, setTopics] = useState(event.topics); useEffect(() => { if (session) { setUser(session.user); } }, [session]); const handleContentChange = useCallback((value) => { setContent(value || ''); }, []); const addLink = () => { setAdditionalLinks([...additionalLinks, '']); } const removeLink = (e, index) => { setAdditionalLinks(additionalLinks.filter((_, i) => i !== index)); } const addTopic = () => { setTopics([...topics, '']); } const removeTopic = (e, index) => { setTopics(topics.filter((_, i) => i !== index)); } const handleLinkChange = (index, value) => { const newLinks = [...additionalLinks]; newLinks[index] = value; setAdditionalLinks(newLinks); }; const handleTopicChange = (index, value) => { const newTopics = [...topics]; newTopics[index] = value; setTopics(newTopics); }; const handleSubmit = async (e) => { e.preventDefault(); try { if (!ndk.signer) { await addSigner(); } // Encrypt content if it's a paid resource let finalContent = content; if (isPaidResource && price > 0) { try { finalContent = await encryptContent(content); if (!finalContent) { showToast('error', 'Error', 'Failed to encrypt content'); return; } } catch (error) { console.error('Encryption error:', error); showToast('error', 'Error', 'Failed to encrypt content: ' + error.message); return; } } const ndkEvent = new NDKEvent(ndk); ndkEvent.kind = event.kind; ndkEvent.content = finalContent; ndkEvent.created_at = Math.floor(Date.now() / 1000); ndkEvent.pubkey = event.pubkey; ndkEvent.tags = [ ['title', title], ['summary', summary], ['image', coverImage], ['t', 'document'], ['d', event.d], ]; // Add topics topics.forEach(topic => { if (topic && topic !== 'document') { ndkEvent.tags.push(['t', topic]); } }); // Add additional links additionalLinks.forEach(link => { if (link) { ndkEvent.tags.push(['r', link]); } }); // Add price if it exists if (price) { ndkEvent.tags.push(['price', price.toString()]); } // Validate the event const validationResult = validateEvent(ndkEvent); if (validationResult !== true) { console.log("validationResult", validationResult); showToast('error', 'Error', validationResult); return; } // Publish the event const signedEvent = await ndk.publish(ndkEvent); if (signedEvent) { // update updated_at for resource in db const updatedResource = await axios.put(`/api/resources/${event.d}`, { updatedAt: new Date().toISOString(), }); if (updatedResource && updatedResource.status === 200) { showToast('success', 'Success', 'Document updated successfully'); router.push(`/details/${updatedResource.data.noteId}`); } else { showToast('error', 'Error', 'Failed to update document'); } } } catch (error) { console.error('Error updating document:', error); showToast('error', 'Error', 'Failed to update document'); } }; return (
); }; export default EditPublishedDocumentForm;