import { usePage } from '@inertiajs/react';
import { useMemo } from 'react';
import { DocumentCommentItem } from '@/features/documents/components/document-comment-item';
import type { DocumentComment } from '@/features/documents/types';
import type { Auth } from '@/types';
import { useI18n } from '@/hooks/use-i18n';

type DocumentCommentsListProps = {
    comments: DocumentComment[];
};

export function DocumentCommentsList({ comments }: DocumentCommentsListProps) {
    const { t } = useI18n();
    const { auth } = usePage<{ auth: Auth }>().props;
    const currentUserId = auth.user?.id ?? null;

    const orderedComments = useMemo(
        () =>
            [...comments].sort(
                (left, right) => new Date(left.created_at).getTime() - new Date(right.created_at).getTime(),
            ),
        [comments],
    );

    if (orderedComments.length === 0) {
        return (
            <div className="flex flex-1 items-center justify-center px-3 py-6 text-center text-xs text-muted-foreground">
                {t('documents.admin_show.comments.empty')}
            </div>
        );
    }

    return (
        <div className="flex min-h-0 flex-1 flex-col justify-end gap-3 overflow-y-auto overscroll-contain px-3 py-3">
            {orderedComments.map((comment) => (
                <DocumentCommentItem
                    key={comment.id}
                    comment={comment}
                    isOwn={currentUserId !== null && comment.author_id === currentUserId}
                />
            ))}
        </div>
    );
}
