import { formatDistanceToNow } from 'date-fns'; import { signIn, useSession } from 'next-auth/react'; import { useState } from 'react'; import { Button, Dialog, TextArea, useToast } from '~/ui'; import ProfilePhotoHolder from '~/components/offers/profile/ProfilePhotoHolder'; import { trpc } from '~/utils/trpc'; import type { Reply } from '~/types/offers'; type Props = Readonly<{ comment: Reply; disableReply?: boolean; handleExpanded?: () => void; isExpanded?: boolean; profileId: string; replyLength?: number; token?: string; }>; export default function CommentCard({ comment: { createdAt, id, message, user }, disableReply, handleExpanded, isExpanded, profileId, replyLength = 0, token = '', }: Props) { const { data: session, status } = useSession(); const [isReplying, setIsReplying] = useState(false); const [currentReply, setCurrentReply] = useState(''); const [isDialogOpen, setIsDialogOpen] = useState(false); const { showToast } = useToast(); const deletable: boolean = token.length > 0 || user?.id === session?.user?.id; const trpcContext = trpc.useContext(); const createCommentMutation = trpc.useMutation(['offers.comments.create'], { onSuccess() { trpcContext.invalidateQueries([ 'offers.comments.getComments', { profileId }, ]); }, }); function handleReply() { if (!currentReply.length) { return; } if (token && token.length > 0) { // If it is with edit permission, send comment to API with username = null createCommentMutation.mutate( { message: currentReply, profileId, replyingToId: id, token, }, { onSuccess: () => { setCurrentReply(''); setIsReplying(false); if (!isExpanded) { handleExpanded?.(); } }, }, ); } else if (status === 'authenticated') { // If not the OP and logged in, send comment to API createCommentMutation.mutate( { message: currentReply, profileId, replyingToId: id, userId: session.user?.id, }, { onSuccess: () => { setCurrentReply(''); setIsReplying(false); if (!isExpanded) { handleExpanded?.(); } }, }, ); } else { // If not the OP and not logged in, direct users to sign in signIn(); } } const deleteCommentMutation = trpc.useMutation(['offers.comments.delete'], { onSuccess() { trpcContext.invalidateQueries([ 'offers.comments.getComments', { profileId }, ]); }, }); function handleDelete() { deleteCommentMutation.mutate( { id, profileId, token, userId: session?.user?.id, }, { onError: () => { showToast({ title: `Server Error`, variant: 'failure' }); }, onSuccess: () => { showToast({ title: `Deleted comment`, variant: 'success' }); }, }, ); } return (
{user?.image ? ( {user?.name ) : ( )}

{user?.name ?? 'Unknown user'}

·
{formatDistanceToNow(createdAt, { addSuffix: true, })}

{message}

{!disableReply && ( )} {replyLength > 0 && ( )} {deletable && ( <> {isDialogOpen && ( { setIsDialogOpen(false); handleDelete(); }} /> } secondaryButton={ )} )}
{!disableReply && isReplying && (
{ event.preventDefault(); event.stopPropagation(); handleReply(); }}>