kontenhumas-fe/components/main/comment-detail-image.tsx

731 lines
22 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { MessageCircle, Share2, Trash2 } from "lucide-react";
import { useRouter, useParams } from "next/navigation";
import {
getArticleDetail,
createArticleComment,
getArticleComments,
deleteArticleComment,
} from "@/service/content/content";
import { getCookiesDecrypt } from "@/lib/utils";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
function getAvatarColor(name: string) {
const colors = [
"#F87171",
"#FB923C",
"#FACC15",
"#4ADE80",
"#60A5FA",
"#A78BFA",
"#F472B6",
];
const index = name.charCodeAt(0) % colors.length;
return colors[index];
}
export default function DetailCommentImage() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [currentUserId, setCurrentUserId] = useState<number | null>(null);
const [article, setArticle] = useState<any>(null);
const [comments, setComments] = useState<any[]>([]);
const [newComment, setNewComment] = useState("");
const [replyParentId, setReplyParentId] = useState<number | null>(null);
const [replyMessage, setReplyMessage] = useState("");
const router = useRouter();
const params = useParams();
const MySwal = withReactContent(Swal);
const id = Number(params?.id);
useEffect(() => {
checkLoginStatus();
if (id) {
fetchArticleDetail(id);
fetchComments(id);
}
}, [id]);
const checkLoginStatus = () => {
const userId = getCookiesDecrypt("urie");
if (userId) {
setIsLoggedIn(true);
setCurrentUserId(Number(userId));
} else {
setIsLoggedIn(false);
setCurrentUserId(null);
}
};
const fetchArticleDetail = async (articleId: number) => {
try {
const res = await getArticleDetail(articleId);
if (res?.data?.data) setArticle(res.data.data);
} catch (error) {
console.error("Gagal memuat artikel:", error);
}
};
const fetchComments = async (articleId: number) => {
try {
const res = await getArticleComments(articleId);
if (res?.data?.data) {
const all = res.data.data.map((c: any) => ({
...c,
parentId: c.parentId ?? 0,
}));
const structured = buildCommentTree(all);
setComments(structured);
}
} catch (error) {
console.error("Gagal memuat komentar:", error);
}
};
const buildCommentTree: any = (comments: any[], parentId = 0) =>
comments
.filter((c) => c.parentId === parentId)
.map((c) => ({
...c,
replies: buildCommentTree(comments, c.id),
}));
const handlePostComment = async () => {
if (!newComment.trim()) {
MySwal.fire("Oops!", "Komentar tidak boleh kosong.", "warning");
return;
}
await sendComment({
articleId: id,
message: newComment,
isPublic: true,
parentId: 0,
});
setNewComment("");
};
const handleReplySubmit = async (parentId: number) => {
if (!replyMessage.trim()) {
MySwal.fire("Oops!", "Balasan tidak boleh kosong.", "warning");
return;
}
await sendComment({
articleId: id,
message: replyMessage,
isPublic: true,
parentId,
});
setReplyMessage("");
setReplyParentId(null);
};
const sendComment = async (payload: any) => {
MySwal.fire({
title: "Mengirim komentar...",
didOpen: () => MySwal.showLoading(),
allowOutsideClick: false,
showConfirmButton: false,
});
try {
const res = await createArticleComment(payload);
if (res?.data?.success || !res?.error) {
MySwal.fire({
icon: "success",
title: "Komentar terkirim!",
timer: 1000,
showConfirmButton: false,
});
fetchComments(id);
} else {
MySwal.fire(
"Gagal",
res.message || "Tidak dapat mengirim komentar.",
"error"
);
}
} catch (error) {
console.error(error);
MySwal.fire(
"Error",
"Terjadi kesalahan saat mengirim komentar.",
"error"
);
}
};
const handleDeleteComment = async (commentId: number) => {
const confirm = await MySwal.fire({
title: "Hapus komentar ini?",
text: "Tindakan ini tidak dapat dibatalkan!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#d33",
cancelButtonColor: "#6b7280",
confirmButtonText: "Ya, hapus",
cancelButtonText: "Batal",
});
if (!confirm.isConfirmed) return;
MySwal.fire({
title: "Menghapus komentar...",
didOpen: () => MySwal.showLoading(),
allowOutsideClick: false,
showConfirmButton: false,
});
try {
const res = await deleteArticleComment(commentId);
if (res?.data?.success || !res?.error) {
MySwal.fire({
icon: "success",
title: "Komentar dihapus!",
timer: 1000,
showConfirmButton: false,
});
fetchComments(id);
} else {
MySwal.fire(
"Gagal",
res.message || "Tidak dapat menghapus komentar.",
"error"
);
}
} catch (error) {
console.error("Gagal menghapus komentar:", error);
MySwal.fire(
"Error",
"Terjadi kesalahan saat menghapus komentar.",
"error"
);
}
};
return (
<div className="max-w-5xl mx-auto p-4 space-y-6">
<button
onClick={() => router.back()}
className="text-sm text-gray-500 hover:underline cursor-pointer"
>
Kembali ke Artikel
</button>
<div>
<p className="font-semibold text-sm uppercase text-gray-600 mb-1">
Comments on:
</p>
<h1 className="text-lg font-bold">
{article?.title || "Memuat judul..."}
</h1>
</div>
<div className="rounded-md p-3 space-y-3 bg-gray-50 border border-gray-200 shadow-sm">
{isLoggedIn ? (
<>
<Textarea
placeholder="Tulis komentar kamu di sini..."
className="min-h-[80px] border border-[#C6A455]"
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
/>
<div className="flex justify-end">
<Button size="sm" onClick={handlePostComment}>
Kirim Komentar
</Button>
</div>
</>
) : (
<>
<Textarea
disabled
placeholder="Tulis komentar kamu di sini..."
className="min-h-[80px] opacity-70"
/>
<Button
onClick={() => router.push("/auth")}
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
>
Sign in and Join the Conversation
</Button>
</>
)}
</div>
{/* Daftar komentar */}
<div className="space-y-6">
{comments.length > 0 ? (
comments.map((comment) => (
<CommentTree
key={comment.id}
comment={comment}
level={0}
replyParentId={replyParentId}
setReplyParentId={setReplyParentId}
replyMessage={replyMessage}
setReplyMessage={setReplyMessage}
onReplySubmit={handleReplySubmit}
onDelete={handleDeleteComment}
currentUserId={currentUserId}
/>
))
) : (
<p className="text-sm text-gray-500 text-center py-4">
Belum ada komentar.
</p>
)}
</div>
</div>
);
}
function CommentTree({
comment,
level,
replyParentId,
setReplyParentId,
replyMessage,
setReplyMessage,
onReplySubmit,
onDelete,
currentUserId,
}: any) {
const color = getAvatarColor(comment.commentFromName || "Anonim");
console.log("🧩 comment.id:", comment.id);
console.log("🧩 commentFromId:", comment.commentFromId);
console.log("🧩 currentUserId:", currentUserId);
const canDelete =
currentUserId &&
(comment.commentFromId == currentUserId ||
comment.userId == currentUserId ||
comment.createdBy == currentUserId);
return (
<div
className={`space-y-3 ${
level > 0 ? "ml-6 border-l-2 border-gray-200 pl-4" : ""
}`}
>
<div className="p-2 rounded-lg transition hover:bg-gray-50 bg-white">
<div className="flex items-start gap-2">
<div
className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold"
style={{ backgroundColor: color }}
>
{comment.commentFromName?.[0]?.toUpperCase() || "U"}
</div>
<div className="flex-1">
<p className="font-semibold text-sm">
{comment.commentFromName}{" "}
<span className="text-gray-500 text-xs font-normal">
{new Date(comment.createdAt).toLocaleString("id-ID")}
</span>
</p>
<p className="text-gray-800 text-sm leading-snug mt-1">
{comment.message}
</p>
<div className="flex items-center gap-3 mt-1 text-xs text-gray-600">
<button
onClick={() =>
setReplyParentId(
replyParentId === comment.id ? null : comment.id
)
}
className="hover:underline flex items-center gap-1"
>
<MessageCircle className="w-3 h-3" /> Reply
</button>
<button className="hover:underline flex items-center gap-1">
<Share2 className="w-3 h-3" /> Share
</button>
{/* ✅ Tombol Delete muncul hanya untuk komentar user login */}
{canDelete && (
<button
onClick={() => onDelete(comment.id)}
className="flex items-center gap-1 px-2 py-1 text-xs bg-red-100 text-red-600 rounded-md hover:bg-red-200"
>
<Trash2 className="w-3 h-3" /> Delete
</button>
)}
</div>
</div>
</div>
{replyParentId === comment.id && (
<div className="mt-3 ml-10 space-y-2">
<Textarea
placeholder={`Balas komentar ${comment.commentFromName}`}
className="min-h-[60px] border border-[#C6A455]"
value={replyMessage}
onChange={(e) => setReplyMessage(e.target.value)}
/>
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setReplyParentId(null)}
>
Batal
</Button>
<Button
variant="outline"
size="sm"
onClick={() => onReplySubmit(comment.id)}
>
Kirim Balasan
</Button>
</div>
</div>
)}
</div>
{comment.replies && comment.replies.length > 0 && (
<div className="space-y-3">
{comment.replies.map((reply: any) => (
<CommentTree
key={reply.id}
comment={reply}
level={level + 1}
replyParentId={replyParentId}
setReplyParentId={setReplyParentId}
replyMessage={replyMessage}
setReplyMessage={setReplyMessage}
onReplySubmit={onReplySubmit}
onDelete={onDelete}
currentUserId={currentUserId}
/>
))}
</div>
)}
</div>
);
}
// "use client";
// import { useState, useEffect } from "react";
// import { Button } from "@/components/ui/button";
// import { Textarea } from "@/components/ui/textarea";
// import {
// ChevronDown,
// Flag,
// MessageCircle,
// Share2,
// ThumbsUp,
// } from "lucide-react";
// import { useRouter, useParams } from "next/navigation";
// import {
// getArticleDetail,
// createArticleComment,
// getArticleComments,
// } from "@/service/content/content";
// import { getCookiesDecrypt } from "@/lib/utils";
// import Swal from "sweetalert2";
// import withReactContent from "sweetalert2-react-content";
// export default function DetailCommentImage() {
// const [isLoggedIn, setIsLoggedIn] = useState(false);
// const [article, setArticle] = useState<any>(null);
// const [comments, setComments] = useState<any[]>([]);
// const [newComment, setNewComment] = useState("");
// const router = useRouter();
// const params = useParams();
// const MySwal = withReactContent(Swal);
// const id = Number(params?.id);
// useEffect(() => {
// checkLoginStatus();
// if (id) {
// fetchArticleDetail(id);
// fetchComments(id);
// }
// }, [id]);
// // ✅ Cek login dari cookies
// const checkLoginStatus = () => {
// const userId = getCookiesDecrypt("urie");
// setIsLoggedIn(!!userId);
// };
// // ✅ Ambil detail artikel
// const fetchArticleDetail = async (articleId: number) => {
// try {
// const res = await getArticleDetail(articleId);
// if (res?.data?.data) setArticle(res.data.data);
// } catch (error) {
// console.error("Gagal memuat artikel:", error);
// }
// };
// // ✅ Ambil komentar dari API
// const fetchComments = async (articleId: number) => {
// try {
// const res = await getArticleComments(articleId);
// if (res?.data?.data) {
// const allComments = res.data.data;
// // Normalisasi parentId (karena ada yg null)
// const normalized = allComments.map((c: any) => ({
// ...c,
// parentId: c.parentId ?? 0,
// }));
// // Susun komentar utama dan balasan
// const rootComments = normalized.filter((c: any) => c.parentId === 0);
// const replies = normalized.filter((c: any) => c.parentId !== 0);
// const structured = rootComments.map((comment: any) => ({
// ...comment,
// replies: replies.filter((r: any) => r.parentId === comment.id),
// }));
// setComments(structured);
// } else {
// setComments([]);
// }
// } catch (error) {
// console.error("Gagal memuat komentar:", error);
// }
// };
// // ✅ Kirim komentar ke API /article-comments
// const handlePostComment = async () => {
// if (!newComment.trim()) {
// MySwal.fire("Oops!", "Komentar tidak boleh kosong.", "warning");
// return;
// }
// MySwal.fire({
// title: "Mengirim komentar...",
// didOpen: () => {
// MySwal.showLoading();
// },
// allowOutsideClick: false,
// allowEscapeKey: false,
// showConfirmButton: false,
// });
// try {
// const payload = {
// articleId: id,
// message: newComment,
// isPublic: true,
// parentId: 0,
// };
// const res = await createArticleComment(payload);
// if (res?.data?.success || !res?.error) {
// MySwal.fire({
// icon: "success",
// title: "Komentar terkirim!",
// text: "Komentar kamu telah ditambahkan.",
// timer: 1200,
// showConfirmButton: false,
// });
// setNewComment("");
// fetchComments(id); // Refresh komentar
// } else {
// MySwal.fire(
// "Gagal",
// res.message || "Tidak dapat mengirim komentar.",
// "error"
// );
// }
// } catch (error) {
// console.error("Error posting comment:", error);
// MySwal.fire(
// "Error",
// "Terjadi kesalahan saat mengirim komentar.",
// "error"
// );
// }
// };
// return (
// <div className="max-w-5xl mx-auto p-4 space-y-6">
// {/* Tombol kembali */}
// <button
// onClick={() => router.back()}
// className="text-sm text-gray-500 hover:underline cursor-pointer"
// >
// ← Kembali ke Artikel
// </button>
// {/* Judul artikel */}
// <div>
// <p className="font-semibold text-sm uppercase text-gray-600 mb-1">
// Comments on:
// </p>
// <h1 className="text-lg font-bold">
// {article?.title || "Memuat judul..."}
// </h1>
// </div>
// {/* Form komentar */}
// <div className="rounded-md p-3 space-y-3">
// {isLoggedIn ? (
// <>
// <Textarea
// placeholder="Tulis komentar kamu di sini..."
// className="min-h-[80px] border border-[#C6A455]"
// value={newComment}
// onChange={(e) => setNewComment(e.target.value)}
// />
// <div className="flex justify-end">
// <Button size="sm" onClick={handlePostComment}>
// Kirim Komentar
// </Button>
// </div>
// </>
// ) : (
// <>
// <Textarea
// disabled
// placeholder="Tulis komentar kamu di sini..."
// className="min-h-[80px] opacity-70"
// />
// <Button
// onClick={() => router.push("/auth")}
// className="w-full bg-blue-600 hover:bg-blue-700 text-white"
// >
// Sign in and Join the Conversation
// </Button>
// </>
// )}
// </div>
// {/* Jumlah & Sort komentar */}
// <div className="flex items-center justify-between border-b pb-2">
// <p className="font-semibold">
// All Comments{" "}
// <span className="text-sm font-medium text-gray-500">
// {comments.length}
// </span>
// </p>
// <div className="flex items-center gap-1 text-sm text-gray-600">
// Sort by
// <button className="flex items-center gap-1 border border-[#C6A455] px-2 py-1 rounded text-gray-700 hover:bg-gray-100">
// Newest <ChevronDown className="w-4 h-4" />
// </button>
// </div>
// </div>
// {/* Daftar komentar */}
// <div className="space-y-6">
// {comments.length > 0 ? (
// comments.map((comment) => (
// <CommentItem
// key={comment.id}
// username={comment.commentFromName || "Anonymous"}
// time={new Date(comment.createdAt).toLocaleString("id-ID", {
// day: "2-digit",
// month: "short",
// year: "numeric",
// hour: "2-digit",
// minute: "2-digit",
// })}
// content={comment.message}
// replies={comment.replies?.map((r: any) => ({
// username: r.commentFromName || "Anonymous",
// time: new Date(r.createdAt).toLocaleString("id-ID", {
// day: "2-digit",
// month: "short",
// year: "numeric",
// hour: "2-digit",
// minute: "2-digit",
// }),
// content: r.message,
// inReplyTo: comment.commentFromName || "Anonymous",
// }))}
// />
// ))
// ) : (
// <p className="text-sm text-gray-500 text-center py-4">
// Belum ada komentar.
// </p>
// )}
// </div>
// </div>
// );
// }
// type Comment = {
// username: string;
// time: string;
// content: string;
// inReplyTo?: string;
// };
// function CommentItem({
// username,
// time,
// content,
// replies,
// }: Comment & { replies?: Comment[] }) {
// return (
// <div className="space-y-3">
// <div>
// <p className="font-semibold">
// {username}{" "}
// <span className="text-gray-500 text-sm font-normal">{time}</span>
// </p>
// <p className="text-gray-800 text-sm">{content}</p>
// <div className="flex items-center gap-4 mt-2 text-sm text-gray-600">
// <ThumbsUp className="w-4 h-4 cursor-pointer" />
// <button className="hover:underline flex items-center gap-1">
// <MessageCircle className="w-4 h-4" /> Reply
// </button>
// <button className="hover:underline flex items-center gap-1">
// <Share2 className="w-4 h-4" /> Share
// </button>
// <button className="ml-auto hover:underline text-gray-400 text-xs flex items-center gap-1">
// <Flag className="w-3 h-3" /> Report
// </button>
// </div>
// </div>
// {replies && replies.length > 0 && (
// <div className="ml-6 border-l pl-4 space-y-3">
// {replies.map((reply, idx) => (
// <div key={idx}>
// <p className="font-semibold">
// {reply.username}{" "}
// <span className="text-gray-500 text-sm font-normal">
// {reply.time}
// </span>
// </p>
// <p className="text-xs text-gray-500">
// In Reply To {reply.inReplyTo}
// </p>
// <p className="text-gray-800 text-sm">{reply.content}</p>
// <div className="flex items-center gap-4 mt-2 text-sm text-gray-600">
// <ThumbsUp className="w-4 h-4 cursor-pointer" />
// <button className="hover:underline flex items-center gap-1">
// <MessageCircle className="w-4 h-4" /> Reply
// </button>
// <button className="hover:underline flex items-center gap-1">
// <Share2 className="w-4 h-4" /> Share
// </button>
// <button className="ml-auto hover:underline text-gray-400 text-xs flex items-center gap-1">
// <Flag className="w-3 h-3" /> Report
// </button>
// </div>
// </div>
// ))}
// </div>
// )}
// </div>
// );
// }