import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import MessageCard from "./MessageCard";
import { User } from "@/types/types";
import React from "react";

interface MessageListProps {
  id: string;
  userDetail: User | undefined;
  refetch: () => void;
}
interface Message {
  _id: string;
  text: string;
  senderId: string;
  createdAt: string;
  file: string;
}
const MessageList = ({ id, userDetail }: MessageListProps) => {
  const { data, isFetchingNextPage } = useInfiniteScroll({
    endpoint: "/tickets/messages",
    queryKey: ["messages", id],
    params: { ticketId: id },
  });

  return (
    <div className="px-4 text-xs md:text-sm">
      <div className="w-full mt-5 pb-10">
        {data?.pages.length === 0 ||
        (data?.pages[0]?.tickets?.length === 0 && !isFetchingNextPage) ? (
          <p className="text-center text-gray-500">نظری وجود ندارد.</p>
        ) : (
          data?.pages?.map((page, pageIndex) => (
            <React.Fragment key={pageIndex}>
              {page?.messages
                ?.slice()
                .reverse()
                .map((item: Message) => (
                  <MessageCard
                    key={item._id}
                    message={item}
                    userDetail={userDetail}
                  />
                ))}
            </React.Fragment>
          ))
        )}
      </div>
    </div>
  );
};

export default MessageList;
