"use client";

import { useRouter } from "next/navigation";

import { Card } from "@/components/ui";
import { ChatItem } from "@/components/widgets";
import { IChat } from "@/entities/chats/types";
import { useChatStore } from "@/providers/chat-store-provider";
import { ROUTES } from "@/shared/constants/client-routes";
import { formatTime } from "@/shared/utils/date";

import styles from "./NewMessages.module.scss";

const getTopPositionItem = (index: number) => {
  return Array.from({ length: index }, (_, i) => i).reduce((acc, current) => {
    return acc + 11 / 1.5 ** current;
  }, 0);
};

interface NewMessagesProps {
  chats: IChat[];
  isVisibleAll: boolean;
  maxHideVisibleCount?: number;
  currentBalance?: number;
}

export default function NewMessages({
  chats,
  isVisibleAll = false,
  maxHideVisibleCount = 3,
  currentBalance = 0,
}: NewMessagesProps) {
  const router = useRouter();
  const setCurrentChat = useChatStore(state => state.setCurrentChat);

  return (
    <Container isVisibleAll={isVisibleAll} chats={chats}>
      {chats
        .slice(0, isVisibleAll ? chats.length : maxHideVisibleCount)
        .map((chat, index) => (
          <ChatItem
            key={chat.id}
            className={styles.newMessage}
            style={
              !isVisibleAll
                ? {
                    top: `${getTopPositionItem(index)}px`,
                    zIndex: 1111 - index,
                    position: !!index ? "absolute" : "relative",
                  }
                : undefined
            }
            userAvatar={{
              src: chat.assistantAvatar,
              alt: chat.assistantName,
              isOnline: chat.assistantStatus === "online",
            }}
            name={chat.assistantName}
            messagePreiew={
              chat.lastMessage
                ? {
                    message: {
                      type: chat.lastMessage.type,
                      content: chat.lastMessage.text,
                      sentWithZeroBalance: chat.lastMessage.sentWithZeroBalance,
                    },
                    currentBalance: currentBalance,
                  }
                : null
            }
            time={formatTime(chat.updatedAt)}
            badgeContent={chat.unreadCount}
            onClick={() => {
              setCurrentChat(chat);
              router.push(ROUTES.chat(chat.assistantId));
            }}
          />
        ))}
    </Container>
  );
}

function Container({
  children,
  isVisibleAll,
  chats,
}: {
  children: React.ReactNode;
  isVisibleAll: boolean;
  chats: IChat[];
}) {
  if (isVisibleAll) {
    return <Card className={styles.card}>{children}</Card>;
  }
  return (
    <div
      className={styles.container}
      style={{
        paddingBottom: getTopPositionItem(chats.length - 1),
      }}
    >
      {children}
    </div>
  );
}
