import { ScrollArea, Stack } from "@mantine/core";
import Message from "./components/Message/Message.tsx";
import MessageInput from "./components/MessageInput/MessageInput.tsx";
import { useChatContext } from "../../pages/ClientsPage/contexts/ChatContext.tsx";
import { MessageSchema } from "../../client";
import { ReactNode } from "react";
import ChatDate from "./components/ChatDate/ChatDate.tsx";

const Chat = () => {
    const {
        messages,
        scrollRef,
        onScrollPositionChange,
    } = useChatContext();

    const getChatElements = (): ReactNode[] => {
        const elements: ReactNode[] = [];
        let prevMessage: MessageSchema | null = null;

        for (let i = messages.length - 1; i >= 0; i--) {
            const currMessage = messages[i];

            if (!prevMessage || prevMessage.createdAt.substring(5, 10) != currMessage.createdAt.substring(5, 10)) {
                elements.push((
                    <ChatDate
                        key={currMessage.id + "date"}
                        date={new Date(currMessage.createdAt)}
                    />
                ));
            }
            elements.push(
                <Message key={currMessage.id + "msg"} message={currMessage} />
            );
            prevMessage = currMessage;
        }

        return elements;
    };

    return (
        <Stack h={"96vh"}>
            <ScrollArea
                h={"100%"}
                viewportRef={scrollRef}
                onScrollPositionChange={onScrollPositionChange}
            >
                <Stack pr={"md"} gap={"sm"}>
                    {getChatElements()}
                </Stack>
            </ScrollArea>
            <MessageInput />
        </Stack>
    );
};

export default Chat;
