// src/components/Post/PostDetail.jsx
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import {
Box,
Center,
Heading,
Text,
Textarea,
Button,
VStack,
HStack,
List,
ListItem,
Spinner,
} from '@chakra-ui/react';
function PostDetail() {
const { id } = useParams();
const [post, setPost] = useState(null);
const [replyContent, setReplyContent] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPost = async () => {
try {
const response = await axios.get(`http://localhost:4000/api/v1/posts/${id}`);
setPost(response.data);
} catch (error) {
console.error('Error fetching post:', error);
} finally {
setLoading(false);
}
};
fetchPost();
}, [id]);
const handleReplySubmit = async () => {
try {
const response = await axios.post(`http://localhost:4000/api/v1/posts/${id}/replies`, {
postId: id,
content: replyContent,
author: 'Student', // You can modify this to get the actual author
});
setPost((prev) => ({
...prev,
replies: [...prev.replies, response.data],
}));
setReplyContent('');
} catch (error) {
console.error('Error submitting reply:', error);
}
};
if (loading) return <Center><Spinner size="xl" /></Center>;
if (!post) return <Center><Text>Post not found.</Text></Center>;
return (
<Center>
<Box p={5} maxWidth="600px" width="100%">
<Heading mb={4}>{post.title}</Heading>
<Text mb={4}>{post.content}</Text>
<Heading size="md" mb={2}>Replies:</Heading>
<List spacing={3}>
{post.replies.map((reply) => (
<ListItem key={reply._id} borderWidth="1px" borderRadius="md" p={3}>
<Text fontWeight="bold">{reply.author}</Text>
<Text>{reply.content}</Text>
</ListItem>
))}
</List>
<VStack spacing={4} mt={6} align="stretch">
<Heading size="md">Leave a reply:</Heading>
<Textarea
value={replyContent}
onChange={(e) => setReplyContent(e.target.value)}
placeholder="Write your reply here..."
size="sm"
resize="vertical"
/>
<HStack justify="flex-end">
<Button colorScheme="teal" onClick={handleReplySubmit}>
Submit
</Button>
</HStack>
</VStack>
</Box>
</Center>
);
}
export default PostDetail;