import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui";
import { ChatComposer, ChatMessages as ChatMessageList, ChatProvider } from "@xtablo/chat-ui";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";

interface ChatMessage {
  id: string;
  userId: string;
  text: string;
  createdAt: string;
  clientId: string;
  optimistic?: boolean;
}

interface Member {
  id: string;
  name: string;
  avatar_url: string | null;
}

interface ChatMessagesProps {
  messages: ChatMessage[];
  currentUserId: string;
  members: Member[];
  typingUsers: string[];
  hasMoreMessages: boolean;
  onLoadMore?: () => void;
  onSend: (text: string) => void;
  onTyping: () => void;
  placeholder?: string;
}

export function ChatMessages({
  messages,
  currentUserId,
  members,
  typingUsers,
  hasMoreMessages: _hasMoreMessages,
  onLoadMore: _onLoadMore,
  onSend,
  onTyping,
  placeholder,
}: ChatMessagesProps) {
  const { t } = useTranslation("chat");
  const membersById = useMemo(() => {
    const map = new Map<string, Member>();
    for (const m of members) {
      map.set(m.id, m);
    }
    return map;
  }, [members]);

  const currentUser = useMemo<ChatUser>(
    () => ({
      id: currentUserId,
      name: membersById.get(currentUserId)?.name ?? t("currentUserName"),
      avatar: membersById.get(currentUserId)?.avatar_url ?? undefined,
    }),
    [currentUserId, membersById, t]
  );

  const chatMessages = useMemo<ChatMessageData[]>(
    () =>
      messages.map((msg) => {
        const member = membersById.get(msg.userId);
        return {
          id: msg.id,
          senderId: msg.userId,
          senderName: member?.name ?? t("defaultUserName"),
          senderAvatar: member?.avatar_url ?? undefined,
          text: msg.text,
          timestamp: new Date(msg.createdAt),
          status: msg.optimistic ? "sending" : undefined,
        };
      }),
    [messages, membersById, t]
  );

  const chatTypingUsers = useMemo<TypingUser[]>(
    () =>
      typingUsers.map((userId) => ({
        id: userId,
        name: membersById.get(userId)?.name ?? t("defaultUserName"),
        avatar: membersById.get(userId)?.avatar_url ?? undefined,
      })),
    [typingUsers, membersById, t]
  );

  const chatLabels = useMemo<ChatLabels>(
    () => ({
      composerPlaceholder: t("placeholder"),
      typingOne: t("typingOne"),
      typingTwo: t("typingTwo"),
      typingMany: t("typingMany"),
      scrollToBottom: t("scrollToBottom"),
    }),
    [t]
  );

  return (
    <ChatProvider currentUser={currentUser} labels={chatLabels} className="flex h-full flex-col">
      <ChatMessageList messages={chatMessages} typingUsers={chatTypingUsers} />
      <ChatComposer
        onSend={onSend}
        onTyping={(_isTyping) => {
          if (_isTyping) onTyping();
        }}
        placeholder={placeholder ?? t("placeholder")}
      />
    </ChatProvider>
  );
}
