import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Panel } from "../Panel";
import { PinnedPanel } from "./components/TableChatRightSection/PinedChatPanel/PinedChatPanel";
import "./TableChatSidePanel.styles.scss";
import TableChatRightSection from "./components/TableChatRightSection/TableChatRightSection";
import TableChatChannelHeader from "./components/TableChatLeftSection/TableChatChannelHeader";
import { Toast as ToastComponent } from "../Toast";
import { Prompt } from "../Prompt";
import ChatSkeleton from "./components/ChatMessageSkeleton/ChatSkeleton";
import ChatMessageListSkeleton from "./components/ChatMessageSkeleton/ChatMessageListSkeleton";
import { EmptyContainer } from "./EmptyContainer";

const defaultChatConfiguration = {
  title: "Chat Feature",
  description: "Chat with the team",
  buttonLabel: "Chat",
  buttonIcon: "chat",
  buttonIconPosition: "left",
};

const TableChatSidePanel = ({ isOpen, handleClose, chatConfiguration }) => {
  const [selectedChannelId, setSelectedChannelId] = useState(null);
  const [selectedChannelInfo, setSelectedChannelInfo] = useState(null);
  const [selectedChatId, setSelectedChatId] = useState(null);
  const [selectedChatInfo, setSelectedChatInfo] = useState(null);

  const [isChatOpen, setIsChatOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isMoreOpen, setIsMoreOpen] = useState(false);
  const [pinnedMsg, setShowPinnedMsg] = useState(false);
  const [showThread, setShowThread] = useState(false);
  const [channelsList, setChannelsList] = useState([]);
  const [chatList, setChatList] = useState([]);
  const [loadingChannelsOrChats, setLoadingChannelsOrChats] = useState(true);
  const [loadingMessages, setLoadingMessages] = useState(false); // right panel messages
  const [originalChatList, setOriginalChatList] = useState([]);
  const [originalChannelList, setOriginalChanelList] = useState([]);
  const [pinnedMessages, setPinnedMessages] = useState([]);
  const [loadingPinned, setLoadingPinned] = useState(false);
  const [threadMessages, setThreadMessages] = useState([]);
  const [loadingThread, setLoadingThread] = useState(false);
  const [openToast, setOpenToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastVariant, setToastVariant] = useState("info");
  const [selectedChat, setSelectedChat] = useState([]);
  const [showDeletePrompt, setShowDeletePrompt] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isCreateNewChatOpen, setIsCreateNewChatOpen] = useState(false);
  const [currentSelectedScreen, setCurrentSelectedScreen] =
    useState("channels");
  const [highlightMessageId, setHighlightMessageId] = useState(null); // For highlighting pinned messages
  const [highlightTrigger, setHighlightTrigger] = useState(0); // Counter to force re-highlight
  const isChannelsScreen = currentSelectedScreen === "channels";
  const selectedChannelOrChatId = isChannelsScreen
    ? selectedChannelId
    : selectedChatId;

  // Extract real-time props from chatConfiguration.messageChatConfig
  const realTimeMessages =
    chatConfiguration?.messageChatConfig?.realTimeMessages || [];
  const isWebSocketConnected =
    chatConfiguration?.messageChatConfig?.isWebSocketConnected || false;
  const currentTopicId =
    chatConfiguration?.messageChatConfig?.currentTopicId || null;
  const onRealTimeMessageUpdate =
    chatConfiguration?.messageChatConfig?.onRealTimeMessageUpdate || null;
  const currentUserId =
    chatConfiguration?.messageChatConfig?.currentUserId || null;

  const handleThreadClick = useCallback(
    async (messageId) => {
      setLoadingThread(true);
      setShowThread(true);

      try {
        const data =
          await chatConfiguration?.messageChatConfig?.loadThreadMessages(
            messageId
          );
        setThreadMessages(data);
      } catch (err) {
        console.error("Error loading thread messages:", err);
      } finally {
        setLoadingThread(false);
      }
    },
    [chatConfiguration?.messageChatConfig?.loadThreadMessages]
  );

  const handlePinMessage = useCallback(
    async (messageId, isPinned, chatId, item) => {
      try {
        const response =
          await chatConfiguration?.messageChatConfig?.onMessagePin(
            messageId,
            isPinned,
            chatId,
            item
          );
        // if exist I need to remove the message from the pinned messages
        //  If not exist I need to add the message to the pinned messages
        if (pinnedMessages.some((message) => message.id === messageId)) {
          const filteredPinnedMessages = pinnedMessages.filter(
            (message) => message.id !== messageId
          );
          setPinnedMessages((prev) => [...filteredPinnedMessages]);
        } else {
          setPinnedMessages((prev) => [...prev, { ...response }]);
        }

        return response;
      } catch (err) {
        console.error("Error while pinning:", err);
      } finally {
      }
    },
    [chatConfiguration?.messageChatConfig?.onMessagePin, pinnedMessages]
  );

  // Memoize messageConfig to prevent unnecessary re-renders
  const memoizedMessageConfig = useMemo(
    () => ({
      ...(chatConfiguration?.messageChatConfig || {}),
      // Real-time message props
      realTimeMessages,
      isWebSocketConnected,
      currentTopicId,
      onRealTimeMessageUpdate,
      currentUserId,
      // Message loading
      loadMessages: chatConfiguration?.rightPanel?.loadMessages,
      // Message cleared trigger
      messagesClearedTrigger:
        chatConfiguration?.rightPanel?.messagesClearedTrigger,
      // Selected message ID for highlighting and scrolling
      // Prioritize dynamic highlightMessageId from pinned click over config
      selectedMessageId:
        highlightMessageId ||
        chatConfiguration?.messageChatConfig?.selectedMessageId,
      // Trigger for pinned message re-highlighting (increment to force re-highlight)
      highlightTrigger: highlightMessageId ? highlightTrigger : null, // Only pass trigger for pinned messages
      // Highlight configuration options
      maxSearchPages: chatConfiguration?.messageChatConfig?.maxSearchPages,
      highlightDuration:
        chatConfiguration?.messageChatConfig?.highlightDuration,
      scrollBehavior: chatConfiguration?.messageChatConfig?.scrollBehavior,
      scrollBlock: chatConfiguration?.messageChatConfig?.scrollBlock,
      highlightColor: chatConfiguration?.messageChatConfig?.highlightColor,
      // Message action handlers
      onMessagePin: handlePinMessage,
      onClearAllMessages:
        chatConfiguration?.messageChatConfig?.onClearAllMessages,
      onThreadClick: (messageId, messageItem) => {
        setShowPinnedMsg(false);
        setShowThread(true);
        handleThreadClick();
        chatConfiguration?.messageChatConfig?.onThreadClick?.(
          messageId,
          messageItem
        );
      },
      // Load participants for mentions
      loadParticipantsAvatar:
        chatConfiguration?.headerChatConfig?.loadParticipantsAvatar,
    }),
    [
      chatConfiguration?.messageChatConfig,
      realTimeMessages,
      isWebSocketConnected,
      currentTopicId,
      onRealTimeMessageUpdate,
      currentUserId,
      chatConfiguration?.rightPanel?.loadMessages,
      chatConfiguration?.rightPanel?.messagesClearedTrigger,
      highlightMessageId, // Dynamic highlight from pinned message click
      highlightTrigger, // Trigger to force re-highlight
      chatConfiguration?.messageChatConfig?.selectedMessageId,
      chatConfiguration?.messageChatConfig?.maxSearchPages,
      chatConfiguration?.messageChatConfig?.highlightDuration,
      chatConfiguration?.messageChatConfig?.scrollBehavior,
      chatConfiguration?.messageChatConfig?.scrollBlock,
      chatConfiguration?.messageChatConfig?.highlightColor,
      handlePinMessage,
      handleThreadClick,
      chatConfiguration?.messageChatConfig?.onThreadClick,
      chatConfiguration?.headerChatConfig?.loadParticipantsAvatar,
    ]
  );

  const handleToast = (isOpen, message = "", variant = "info") => {
    if (isOpen) {
      setOpenToast(isOpen);
      setToastMessage(message);
      setToastVariant(variant);
    } else {
      setOpenToast(false);
      setToastMessage("");
      setToastVariant("info");
    }
  };

  // Once user click on a chat, then we will set the selected chat id and info
  const handleChatClick = async (chatId, selectedChatData) => {
    setCurrentSelectedScreen("chats");
    setLoadingMessages(true); // 👈 show skeleton
    setSelectedChatId(chatId);
    setSelectedChatInfo(selectedChatData);
    setHighlightMessageId(null); // Reset highlight when switching chats
    try {
      if (chatConfiguration?.headerChatConfig?.onChatClick) {
        await chatConfiguration.headerChatConfig.onChatClick(
          chatId,
          selectedChannelId
        );
      }
      // Messages will be loaded directly in TableChatRightSection
    } catch (err) {
      console.error("[TableChatSidePanel] [handleChatClick] [error]:", err);
      handleToast(true, "Error loading chat", "error");
    } finally {
      setLoadingMessages(false); // 👈 hide skeleton
    }
  };

  const fetchChatList = async (currentActiveChannelInfo) => {
    setCurrentSelectedScreen("chats");
    setSelectedChat([]); // Clear selected chats when switching channels
    if (chatConfiguration?.leftPanel?.loadChatList) {
      setLoadingChannelsOrChats(true);
      try {
        const chatList = await chatConfiguration.leftPanel.loadChatList(
          currentActiveChannelInfo
        );
        setChatList(chatList);
        setOriginalChatList(chatList);
        return chatList;
      } catch (err) {
        console.error("[TableChatSidePanel] [fetchChatList] [error]:", err);
        handleToast(true, "Error while loading chats", "error");
      } finally {
        setLoadingChannelsOrChats(false);
      }
    }
  };

  const handleChatName = async (formData, selectedChannelId) => {
    try {
      // Call the original handleChatName function
      const response = await chatConfiguration?.leftPanel?.handleChatName?.(
        formData,
        selectedChannelId
      );
      // If successful, refresh the chat list and auto-select the new chat
      if (response?.success) {
        setIsCreateNewChatOpen(false);
        // Auto-select and open the newly created chat
        if (response?.formattedChat) {
          const newChat = response.formattedChat;
          const newChannelInfo = {
            id: newChat?.otherProps?.object_ids?.[0],
            title: "Chat List",
            objectType: newChat?.otherProps?.object_type, // or get from configuration
          };
          await fetchChatList(newChannelInfo);
          // If user direclty coming from create new chat panel, then set the selected channel info and id (both will null on that time)
          setSelectedChannelInfo(newChannelInfo);
          setSelectedChannelId(newChat?.otherProps?.object_ids?.[0]);
          // Then I want newly created chat to be selected
          await handleChatClick(newChat.id, newChat);
        }
      }

      return response;
    } catch (error) {
      console.error("[TableChatSidePanel] [handleChatName] [error]:", error);
      throw error;
    }
  };

  // Fetch the channel list
  const fetchChannelList = async () => {
    setCurrentSelectedScreen("channels");
    setLoadingChannelsOrChats(true);
    try {
      const channelList = await chatConfiguration.leftPanel.loadChannelsList();
      setChannelsList(channelList);
      setOriginalChanelList(channelList);
    } catch (error) {
      console.error("[TableChatSidePanel] [fetchChannelList] [error]:", error);
      handleToast(true, "Error while loading channels", "error");
    } finally {
      setLoadingChannelsOrChats(false);
    }
  };

  const fetchChannelsOrChats = async () => {
    setLoadingChannelsOrChats(true);
    try {
      // Once user click on a chat icon in the table , then we will set the selected chat id and info
      if (
        chatConfiguration?.leftPanel?.hasDirectChatList &&
        chatConfiguration?.leftPanel?.directChatList?.length > 0
      ) {
        // Set the current selected screen to chats (Opening chat panel) not the channels panel
        setCurrentSelectedScreen("chats");
        // Set up for direct chat list display(directChatList=all chats list related to the channel)
        const directChatList = chatConfiguration.leftPanel.directChatList;
        // Set the chat list and original chat list
        setChatList(directChatList);
        setOriginalChatList(directChatList);
        // Create a fake channel info for the direct chat list
        const channelInfo = {
          id: directChatList?.[0]?.otherProps?.object_ids?.[0],
          title: "Chat List",
          objectType: directChatList?.[0]?.otherProps?.object_type, // or get from configuration
        };
        // Set the selected channel id and info
        setSelectedChannelId(directChatList?.[0]?.otherProps?.object_ids?.[0]);
        setSelectedChannelInfo(channelInfo);

        // Automatically open a specific chat or the first chat (index 0)
        if (directChatList.length > 0) {
          // Check if a specific chatId is provided in configuration
          const selectedChatId = chatConfiguration?.leftPanel?.selectedChatId;

          let chatToSelect;
          if (selectedChatId) {
            // Find the specific chat by ID
            chatToSelect = directChatList.find(
              (chat) => chat.id === selectedChatId
            );
            // If specific chat not found, fall back to first chat
            if (!chatToSelect) {
              chatToSelect = directChatList?.[0];
            }
          } else {
            // No specific chat ID provided, select first chat
            chatToSelect = directChatList?.[0];
          }

          // Select the determined chat
          await handleChatClick(chatToSelect?.id, chatToSelect);
        }
      } else if (
        chatConfiguration?.leftPanel?.hasDirectChatList &&
        chatConfiguration?.leftPanel?.directChatList?.length === 0
      ) {
        // Set the current selected screen to chats (Opening chat panel) not the channels panel
        setCurrentSelectedScreen("chats");
        // This is open create new chat panel
        setIsCreateNewChatOpen(true);
      } else {
        //  Normal channel loading flow (if user directly coming by clicking on global general chat icon)
        await fetchChannelList();
      }
    } catch (error) {
      console.error("[TableChatSidePanel] [fetchChannels] [error]:", error);
      handleToast(true, "Error while loading channels list", "error");
    } finally {
      setLoadingChannelsOrChats(false);
    }
  };

  const clearnupLocalStates = () => {
    setSelectedChannelId(null);
    setSelectedChannelInfo(null);
    setSelectedChatInfo(null);
    setSelectedChatId(null);
    setChatList([]);
    setOriginalChatList([]);
    setSelectedChat([]);
    setShowPinnedMsg(false);
    setShowThread(false);
    setPinnedMessages([]);
    setThreadMessages([]);
    setIsSearchOpen(false);
    setIsMoreOpen(false);
    setHighlightMessageId(null); // Reset highlight when cleaning up
  };

  // Handle back button click - clear direct chat and load channels
  const handleBackToChannels = async () => {
    // Clear direct chat list in parent component
    if (chatConfiguration?.leftPanel?.clearDirectChatList) {
      chatConfiguration.leftPanel.clearDirectChatList();
    }
    // Reset states
    clearnupLocalStates();
    // Fetch the channel list when user click on back button
    await fetchChannelList();
  };

  // Once chat side panel is open, then fetch the channels or chats
  useEffect(() => {
    if (isOpen) {
      fetchChannelsOrChats();
    }
  }, [isOpen]);

  // Once chat side panel is closed, then reset all states
  useEffect(() => {
    if (!isOpen) {
      // Reset all states when panel is closed
      clearnupLocalStates();

      // Clear direct chat list in the parent component
      if (chatConfiguration?.leftPanel?.clearDirectChatList) {
        chatConfiguration.leftPanel.clearDirectChatList();
      }
    }
  }, [isOpen]); // Remove clearDirectChatList from dependencies to prevent infinite loop

  // Clear highlightMessageId after highlight duration to prevent re-highlighting on new messages
  useEffect(() => {
    if (highlightMessageId) {
      // Get highlight duration from config or use default (3000ms = 3 seconds)
      const highlightDuration =
        chatConfiguration?.messageChatConfig?.highlightDuration || 3000;

      // Set timeout to clear highlight after animation completes
      const timeoutId = setTimeout(() => {
        setHighlightMessageId(null);
      }, highlightDuration);

      // Cleanup timeout if highlightMessageId changes or component unmounts
      return () => {
        clearTimeout(timeoutId);
      };
    }
  }, [
    highlightMessageId,
    chatConfiguration?.messageChatConfig?.highlightDuration,
  ]);

  // const openChat = () => setIsChatOpen(true);
  const toggleMenu = () => setIsMoreOpen(!isMoreOpen);
  const openSearch = () => setIsSearchOpen(!isSearchOpen);
  const showMore = () => setIsMoreOpen(true);

  const handlePinnedClick = async (chatId) => {
    setLoadingPinned(true);
    try {
      const data = await chatConfiguration?.headerChatConfig?.onPinnedClick(
        chatId
      );
      setPinnedMessages(data);
    } catch (err) {
      console.error("[TableChatSidePanel] [handlePinnedClick] [error]:", err);
    } finally {
      setLoadingPinned(false);
    }
  };

  // Handle click on a pinned message to highlight it in main chat
  const handlePinnedMessageClick = (messageId) => {
    // Don't close the pinned panel - keep it open for reference

    // Set the message ID to highlight
    setHighlightMessageId(messageId);

    // Increment trigger to force re-highlight even if same message clicked again
    setHighlightTrigger((prev) => prev + 1);
  };

  const handleChannelClick = async (selectedChannelId, selectedChannelInfo) => {
    setSelectedChannelId(selectedChannelId);
    setSelectedChannelInfo(selectedChannelInfo);
    const chatList = await fetchChatList(selectedChannelInfo); // Fetch the chat list when user click on a channel
    // select the first chat
    if (chatList && chatList.length > 0) {
      const firstChat = chatList?.[0];
      await handleChatClick(firstChat?.id, firstChat);
    }
  };

  // Function to handle chat selection (for delete functionality)
  const handleChatSelect = (selectedChatId) => {
    setSelectedChat(
      (prev) =>
        prev.includes(selectedChatId)
          ? prev.filter((id) => id !== selectedChatId) // remove
          : [...prev, selectedChatId] // add
    );
  };

  const filterChannelsByTitle = useCallback(
    (searchText) => {
      const targetList = isChannelsScreen
        ? originalChannelList
        : originalChatList;
      if (!searchText) {
        // reset original lists
        if (isChannelsScreen) {
          setChannelsList(originalChannelList);
        } else {
          setChatList(originalChatList);
        }
        return;
      }

      const filtered =
        targetList?.filter((ch) =>
          ch.title.toLowerCase().includes(searchText.toLowerCase())
        ) || [];

      if (isChannelsScreen) {
        // Ensure we're creating a new array reference
        setChannelsList([...filtered]);
      } else {
        setChatList([...filtered]);
      }
    },
    [isChannelsScreen, originalChannelList, originalChatList]
  );

  // Handle opening delete prompt
  const handleDeletePromptOpen = () => {
    if (!selectedChat || selectedChat.length === 0) {
      handleToast(true, "No chats selected for deletion", "error");
      return;
    }
    setShowDeletePrompt(true);
  };

  // Handle the actual deletion process
  const handleDeleteChat = async () => {
    if (!selectedChat || selectedChat.length === 0) {
      handleToast(true, "No chats selected for deletion", "error");
      return;
    }

    try {
      // Show loading state
      setIsDeleting(true);
      // setLoadingChannelsOrChats(true);

      // Check if any of the deleted topics is currently active
      const isActiveTopicDeleted = selectedChat.includes(selectedChatId);

      // Delete all selected topics using Promise.all
      const deletePromises = selectedChat.map((topicId) =>
        chatConfiguration?.leftPanel?.deleteChat?.(topicId)
      );

      await Promise.all(deletePromises);
      setShowDeletePrompt(false);
      setIsDeleting(false);

      // Close the prompt after successful deletion

      // Clear selected chats after successful deletion
      setSelectedChat([]);

      // Mark all deleted topics as deleted to prevent reconnection
      if (chatConfiguration?.messageChatConfig?.markTopicAsDeleted) {
        selectedChat.forEach((topicId) => {
          chatConfiguration?.messageChatConfig?.markTopicAsDeleted(topicId);
        });
      }

      // If active topic was deleted, handle cleanup
      if (isActiveTopicDeleted) {
        // 1. Disconnect WebSocket for the deleted topic
        if (chatConfiguration?.messageChatConfig?.leaveCurrentTopic) {
          chatConfiguration?.messageChatConfig?.leaveCurrentTopic();
        }

        // 2. Reset message list to ideal state
        setPinnedMessages([]);
        setThreadMessages([]);
        // 3. Clear selected chat info (no chat selected state)
        setSelectedChatInfo(null);
        setSelectedChatId(null);
      }

      // Refresh chat list after successful deletion
      if (selectedChannelInfo) {
        const updatedChatList = await fetchChatList(selectedChannelInfo);

        // If active topic was deleted and there are remaining chats, auto-select the first one
        if (
          isActiveTopicDeleted &&
          updatedChatList &&
          updatedChatList.length > 0
        ) {
          const firstChat = updatedChatList?.[0];
          await handleChatClick(firstChat.id, firstChat);
        }
      }
    } catch (error) {
      console.error("[TableChatSidePanel] [handleDeleteChat] [error]:", error);
      handleToast(true, "Error deleting topics", "error");

      // Keep prompt open on error so user can retry or cancel
    } finally {
      setIsDeleting(false);
      setLoadingChannelsOrChats(false);
    }
  };

  return (
    <aside id="table-chat-side-panel">
      <Panel
        anchor="right"
        className={"table-chat-panel"}
        open={isOpen}
        onClose={handleClose}
        title={chatConfiguration?.title}
        size="medium"
        setIsOpen={() => setIsChatOpen(!isChatOpen)}
        width={pinnedMsg || showThread ? 1450 : 985}
      >
        <div className="table-chat-container">
          <TableChatChannelHeader
            title={
              isChannelsScreen ? "Channels List" : selectedChannelInfo?.title
            }
            channels={isChannelsScreen ? channelsList : chatList}
            selectedChannelOrChatId={selectedChannelOrChatId}
            onBack={handleBackToChannels} // 👈 back click => load channels with loader
            onChannelSelect={(id, selectedChannelOrChat) => {
              if (isChannelsScreen) {
                handleChannelClick(id, selectedChannelOrChat);
              } else {
                // for chat render
                handleChatClick(id, selectedChannelOrChat);
              }
            }}
            showChannelList={isChannelsScreen}
            onMenuClick={toggleMenu}
            onSearchClick={openSearch}
            onMoreClick={showMore}
            isSearchOpen={isSearchOpen}
            headerConfig={chatConfiguration?.leftPanel?.leftHeaderPanel}
            showAddChatBtn={
              chatConfiguration?.leftPanel?.leftHeaderPanel?.showAddChat
            }
            showCheckbox={
              chatConfiguration?.leftPanel?.leftChatPanel?.showCheckbox
            }
            handleChatName={handleChatName}
            onPinnedChatClick={
              chatConfiguration?.headerChatConfig?.onPinnedChatClick
            }
            filterChannelsByTitle={filterChannelsByTitle}
            loadingChannels={loadingChannelsOrChats}
            handleToast={handleToast}
            selectedChannelInfo={selectedChannelInfo}
            onDeleteTopics={handleDeletePromptOpen}
            selectedChat={selectedChat}
            handleChatSelect={handleChatSelect}
            isCreateNewChatOpen={isCreateNewChatOpen}
            setIsCreateNewChatOpen={setIsCreateNewChatOpen}
          />

          {/*Right section starts here */}
          {loadingMessages ? (
            <ChatSkeleton text="Loading messages..." />
          ) : (
            <>
              {!selectedChannelId || !selectedChatId ? (
                <EmptyContainer
                  title={
                    !selectedChannelId
                      ? chatConfiguration?.messageChatConfig
                          ?.emptyChannelStateTitle
                      : !selectedChatId
                      ? chatConfiguration?.messageChatConfig
                          ?.emptyChatStateTitle
                      : ""
                  }
                  subTitle={
                    !selectedChannelId
                      ? chatConfiguration?.messageChatConfig
                          ?.emptyChannelStateSubTitle
                      : !selectedChatId
                      ? chatConfiguration?.messageChatConfig
                          ?.emptyChatStateSubTitle
                      : ""
                  }
                />
              ) : (
                <TableChatRightSection
                  // Basic props
                  chatId={selectedChatId}
                  title={selectedChatInfo?.title}
                    CreatedBy={
                    selectedChatInfo?.otherProps?.created_by_user ??
                    selectedChatInfo?.createdBy ??
                    selectedChatInfo?.user ??
                    "—"
                  }
                  createdAt={
                    selectedChatInfo?.timestamp ??
                    selectedChatInfo?.createdAt ??
                    (selectedChatInfo?.otherProps?.created_at
                      ? new Date(
                          selectedChatInfo.otherProps.created_at
                        ).toLocaleString(undefined, {
                          dateStyle: "medium",
                          timeStyle: "short",
                        })
                      : "")
                  }
                  // Header configuration
                  chatHeaderConfig={{
                    ...chatConfiguration?.headerChatConfig,
                    onPinnedClick: (chatId) => {
                      setShowThread(false);
                      setShowPinnedMsg(true);
                      handlePinnedClick(chatId);
                    },
                  }}
                  messageConfig={memoizedMessageConfig}
                  showParticipantsList={
                    chatConfiguration?.leftPanel?.rightHeaderPanel
                      ?.showParticipants
                  }
                  showPinnedChat={
                    chatConfiguration?.leftPanel?.rightHeaderPanel
                      ?.showPinnedChat
                  }
                  showSearch={
                    chatConfiguration?.leftPanel?.rightHeaderPanel
                      ?.showChatSearch
                  }
                  setPinnedMessages={setPinnedMessages}
                  showActionBtn={
                    chatConfiguration?.leftPanel?.rightHeaderPanel
                      ?.showActionBtn
                  }
                  handleToast={handleToast}
                  inputChatConfig={{
                    ...chatConfiguration.inputChatConfig,
                  }}
                />
              )}
            </>
          )}
          {loadingPinned ? (
            <>
              {/* List item skeletons */}
              <ChatMessageListSkeleton
                className="thread-skeleton"
                messageCount={5}
              />

              {/* Bottom action skeleton  */}
            </>
          ) : (
            <>
              {pinnedMsg && (
                <PinnedPanel
                  messages={pinnedMessages}
                  onClose={() => setShowPinnedMsg(!pinnedMsg)}
                  handleToast={handleToast}
                  onMessageClick={handlePinnedMessageClick}
                />
              )}
            </>
          )}
          {loadingThread ? (
            <>
              {/* Header skeleton */}

              {/* List item skeletons */}
              {/* <SkeletonList text="Loading messages..." /> */}
              <ChatMessageListSkeleton
                className="thread-skeleton"
                messageCount={5}
              />

              {/* Bottom action skeleton  */}
            </>
          ) : (
            <>
              {showThread && (
                <PinnedPanel
                  type="thread"
                  messages={threadMessages}
                  onClose={() => setShowThread(!showThread)}
                  handleToast={handleToast}
                />
              )}
            </>
          )}
        </div>
      </Panel>

      {/* Delete Confirmation Prompt */}
      <Prompt
        handleClose={() => {
          if (!isDeleting) {
            setShowDeletePrompt(false);
          }
        }}
        isOpen={showDeletePrompt || isDeleting}
        onPrimaryButtonClick={() => {
          if (!isDeleting) {
            handleDeleteChat();
          }
        }}
        onSecondaryButtonClick={() => {
          if (!isDeleting) {
            setShowDeletePrompt(false);
          }
        }}
        primaryButtonLabel={isDeleting ? "Deleting..." : "Delete"}
        secondaryButtonLabel="Cancel"
        title="Delete Chats"
        variant="error"
        primaryButtonProps={{
          disabled: isDeleting,
          loading: isDeleting,
        }}
      >
        Are you sure you want to delete {selectedChat?.length} selected chat
        {selectedChat?.length > 1 ? "s" : ""}? This action cannot be undone.
      </Prompt>

      <ToastComponent
        isOpen={openToast}
        message={toastMessage}
        onClose={() => setOpenToast(!openToast)}
        position="top-right"
        variant={toastVariant}
      />
    </aside>
  );
};

export default TableChatSidePanel;
