"use client"; import axios from "axios"; import { ApiServerBaseUrl } from "@/utils/baseurl.utils"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { getSocialAuthStatus } from "@/utils/commonFunction.utils"; import SocialCommentItem from "@/components/SocialCommentItem"; import { Image as ImageIcon, Video, MessageSquare, Heart, Calendar, ExternalLink, Send, RefreshCw, ChevronLeft, MoreVertical, BarChart3, Users, Clock, Shield, AlertCircle, CheckCircle } from "lucide-react"; type Reply = { id: string; text: string; timestamp: string; username: string; hidden?: boolean; like_count?: number; }; type Comment = { id: string; text: string; username: string; timestamp: string; like_count?: number; hidden?: boolean; replies?: { data: Reply[] }; }; type MediaDetails = { id: string; media_url: string; caption?: string; media_type: string; timestamp: string; like_count?: number; comments_count?: number; permalink?: string; }; const MediaDetailsPage = ({ params }: { params: { id: string } }) => { const { id } = params; const router = useRouter(); const [media, setMedia] = useState(null); const [comments, setComments] = useState([]); const [loading, setLoading] = useState(true); const [commentsLoading, setCommentsLoading] = useState(false); const [newCommentText, setNewCommentText] = useState(""); const [error, setError] = useState(""); const [refreshing, setRefreshing] = useState(false); useEffect(() => { async function validate() { const userEmail = localStorage.getItem("user_email"); if (!userEmail) { router.push("/social-media-connect"); return; } const storedUser = localStorage.getItem("userDetails"); if (!storedUser) { router.push("/social-media-connect"); return; } const user = JSON.parse(storedUser); const role = user?.role; if (role === "customer") { const session = localStorage.getItem("payment_session"); if (!session) { router.push("/pricing"); return; } } const res = await getSocialAuthStatus(userEmail); if (!res?.connected) { router.push("/social-media-connect"); return; } } validate(); }, []); // Fetch Media Details useEffect(() => { const fetchMedia = async () => { try { const res = await axios.get(`${ApiServerBaseUrl}/social/media/${id}?userId=${localStorage.getItem( "user_email" )}`); setMedia(res.data); } catch (err: any) { setError(err.response?.data?.message || "Unable to load media"); } finally { setLoading(false); } }; fetchMedia(); }, [id]); // Fetch Comments const loadComments = async () => { setCommentsLoading(true); try { const res = await axios.get( `${ApiServerBaseUrl}/social/media/${id}/comments?userId=${localStorage.getItem( "user_email" )}` ); setComments(res.data?.data || []); } catch { console.error("Failed to load comments"); } finally { setCommentsLoading(false); } }; useEffect(() => { if (media) loadComments(); }, [media]); // Post new top-level comment const postNewComment = async () => { if (!newCommentText.trim()) { alert("Comment cannot be empty."); return; } try { const res = await axios.post( `${ApiServerBaseUrl}/social/media/${id}/comments?userId=${localStorage.getItem( "user_email" )}`, { message: newCommentText } ); const newComment: Comment = { id: res.data?.comment_id || res.data?.id || `temp-${Date.now()}`, text: newCommentText, username: "Me", timestamp: new Date().toISOString(), replies: { data: [] } }; setComments((prev) => [newComment, ...prev]); setNewCommentText(""); } catch (err: any) { alert(err.response?.data?.error || "Failed to post comment."); } }; // Reply handler const handleReply = async (commentId: string, text: string) => { try { const res = await axios.post( `${ApiServerBaseUrl}/social/comments/${commentId}/reply?userId=${localStorage.getItem( "user_email" )}`, { message: text } ); const newReply: Reply = { id: res.data?.reply_id || res.data?.id || `temp-${Date.now()}`, text: text, username: "Me", timestamp: new Date().toISOString(), }; setComments((prev) => prev.map((cm) => cm.id === commentId ? { ...cm, replies: { data: [...(cm.replies?.data || []), newReply], }, } : cm ) ); } catch (err: any) { alert(err.response?.data?.error || "Reply failed."); } }; // Delete handler const handleDelete = async (id: string, isReply: boolean = false, parentId?: string) => { const confirmed = window.confirm("Are you sure you want to delete this?"); if (!confirmed) return; try { await axios.delete(`${ApiServerBaseUrl}/social/comments/${id}?userId=${localStorage.getItem( "user_email" )}`); if (isReply && parentId) { setComments((prev) => prev.map((cm) => { if (cm.id === parentId) { return { ...cm, replies: { data: cm.replies?.data.filter((r) => r.id !== id) || [], }, }; } return cm; }) ); } else { setComments((prev) => prev.filter((c) => c.id !== id)); } } catch (err: any) { alert("Delete failed: " + (err.response?.data?.error || err.message)); } }; // Hide/Unhide handler const handleHide = async (id: string, currentStatus: boolean, isReply: boolean = false) => { try { const newHideStatus = !currentStatus; await axios.post(`${ApiServerBaseUrl}/social/comments/${id}/hide?userId=${localStorage.getItem("user_email")}`, { hide: newHideStatus, }); if (isReply) { setComments((prev) => prev.map((cm) => { const replyIndex = cm.replies?.data.findIndex(r => r.id === id); if (replyIndex !== undefined && replyIndex !== -1 && cm.replies?.data) { const updatedReplies = [...cm.replies.data]; updatedReplies[replyIndex] = { ...updatedReplies[replyIndex], hidden: newHideStatus }; return { ...cm, replies: { data: updatedReplies } }; } return cm; }) ); } else { setComments((prev) => prev.map((c) => (c.id === id ? { ...c, hidden: newHideStatus } : c)) ); } } catch (err: any) { alert(err.response?.data?.error || "Hide/Unhide failed."); } }; // Edit handler const handleEdit = async (id: string, newText: string, isReply: boolean = false, parentId?: string) => { if (id.toString().startsWith("temp-") || id.toString().startsWith("new-")) { alert("Please refresh the page to get the real ID from Instagram before editing this comment again."); return; } const confirmed = window.confirm( "Compatible Edit Mode:\n\nInstagram does not allow editing comments directly.\n\nProceeding will DELETE the original comment (losing likes/replies) and POST a new one with the updated text.\n\nDo you want to continue?" ); if (!confirmed) return; try { await axios.delete(`${ApiServerBaseUrl}/social/comments/${id}?userId=${localStorage.getItem("user_email")}`); let res; if (isReply && parentId) { res = await axios.post( `${ApiServerBaseUrl}/social/comments/${parentId}/reply?userId=${localStorage.getItem("user_email")}`, { message: newText } ); } else { res = await axios.post( `${ApiServerBaseUrl}/social/media/${media?.id}/comments?userId=${localStorage.getItem("user_email")}`, { message: newText } ); } const newId = res.data?.id || res.data?.comment_id || res.data?.reply_id; const safeId = newId || `new-${Date.now()}`; if (isReply && parentId) { setComments((prev) => prev.map((cm) => { if (cm.id === parentId) { const oldReplies = cm.replies?.data || []; const filteredReplies = oldReplies.filter((r) => r.id !== id); const newReplyObj: Reply = { id: safeId, text: newText, username: "Me", timestamp: new Date().toISOString(), hidden: false, like_count: 0 }; return { ...cm, replies: { data: [...filteredReplies, newReplyObj] } }; } return cm; }) ); } else { setComments((prev) => { const filtered = prev.filter((c) => c.id !== id); const newCommentObj: Comment = { id: safeId, text: newText, username: "Me", timestamp: new Date().toISOString(), like_count: 0, hidden: false, replies: { data: [] } }; return [newCommentObj, ...filtered]; }); } } catch (err: any) { console.error(err); alert("Edit failed: " + (err.response?.data?.error || err.message)); } }; // Refresh comments const handleRefreshComments = async () => { setRefreshing(true); await loadComments(); setTimeout(() => setRefreshing(false), 1000); }; // Format date const formatDate = (timestamp: string) => { const date = new Date(timestamp); return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }; if (loading) return (

Loading media details...

); if (error) return (

Error Loading Media

{error}

); if (!media) return (

No media found.

); return (
{/* Floating background bubbles */}
{/* Header */}

Post Details

Manage comments and view post details

{/* Main Content */}
{/* Left Column - Media */}
{/* Media Card */}
{/* Media Display */}
{media.media_type === "VIDEO" ? (
{/* Media Details */}
{media.caption && (

Caption

{media.caption}

)} {/* Stats Grid */}
Likes
{media.like_count || 0}
Comments
{media.comments_count || 0}
Posted
{new Date(media.timestamp).toLocaleDateString()}
Time
{new Date(media.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
{/* View on Instagram Button */} {media.permalink && ( View on Instagram )}
{/* New Comment Input */}

Add a Comment