import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ChatListRes, OuterChat, PeerUserData } from "../../types/ChatListType";
import { insertChatSorted } from "../../utils/insertChatSorted";

// Define the initial state with an empty chatList
const initialState: ChatListRes = {
  pagination: {
    total_pages: 0,
    total_records: 0,
    current_page: 0,
    records_per_page: 0,
  },
  Chats: [],
};

// Create a slice of the state
const ArchiveListSlice = createSlice({
  name: "archiveList",
  initialState,
  reducers: {
    // Reducer to update the chatList
    updateArchiveList(state, action: PayloadAction<ChatListRes>) {
      // console.log("action.payload", action.payload);
      // Directly modify the state to replace the chatList
      return action.payload;
    },

    updateArchiveListByChatId(
      state,
      action: PayloadAction<{
        chat_id: number;
        last_message: string;
        last_message_type: string;
      }>, // single object in payload
    ) {
      // console.log(action.payload, "action.payload");

      state.Chats[0].Records.map((conversation) => {
        if (conversation.chat_id == action.payload.chat_id) {
          return {
            ...conversation,
            last_message: action.payload.last_message,
            last_message_type: action.payload.last_message_type,
          };
        }
        return conversation;
      });
    },
    updateArchiveListForNewMessage(
      state,
      action: PayloadAction<{
        chat_id: number;
        last_message: string;
        last_message_type: string;
        peerUserData?: PeerUserData; // Optional: used only when chat doesn't exist
        createdAt?: Date; // Optional: used to create a new chat
        cleared_for?: string[];
      }>,
    ) {
      const {
        chat_id,
        last_message,
        last_message_type,
        peerUserData,
        createdAt,
        cleared_for,
      } = action.payload;

      // Find chat index by chat_id
      const existingIndex = state.Chats.findIndex(
        (chat) => chat.Records[0].chat_id === chat_id,
      );

      if (existingIndex !== -1) {
        // Update the message content and type
        const updatedChat = {
          ...state.Chats[existingIndex],
          Records: [
            {
              ...state.Chats[existingIndex].Records[0],
              cleared_for: cleared_for,
              Messages: [
                {
                  ...state.Chats[existingIndex].Records[0].Messages[0],
                  message_content: last_message,
                  message_type: last_message_type,
                  updatedAt: new Date(),
                },
              ],
            },
          ],
        };

        // Remove the chat from its current position
        state.Chats.splice(existingIndex, 1);
        // Insert it at the top
        state.Chats.unshift(updatedChat);
      } else {
        // Create a new chat structure
        const newChat = {
          Records: [
            {
              chat_id,
              chat_type: "private", // or "group" - depends on your logic
              group_name: "",
              group_icon: "",
              group_description: "",
              deleted_at: null,
              is_group_blocked: false,
              createdAt: createdAt || new Date(),
              updatedAt: new Date(),
              deletedAt: null,
              Messages: [
                {
                  message_content: last_message,
                  message_type: last_message_type,
                  message_length: "",
                  message_seen_status: "sent",
                  message_size: "",
                  deleted_for: [],
                  starred_for: [],
                  deleted_for_everyone: false,
                  pinned: false,
                  pin_lifetime: null,
                  peer_user: null,
                  pinned_till: null,
                  forwarded_from: 0,
                  createdAt: new Date(),
                  updatedAt: new Date(),
                  chat_id,
                  sender_id: peerUserData?.user_id || 0,
                  message_id: Date.now(), // dummy
                  reply_to: 0,
                  social_id: 0,
                  User: peerUserData!,
                  ActionedUser: null,
                },
              ],
              unseen_count: 1,
            },
          ],
          PeerUserData: peerUserData!,
        };

        // Insert new chat at top
        state.Chats.unshift(newChat);
      }
    },
    updateArchiveListUnreadCountByChatId(
      state,
      action: PayloadAction<{
        chat_id: number;
      }>,
    ) {
      const conversation = state.Chats[0].Records.find(
        (conv) => conv.chat_id == action.payload.chat_id,
      );

      if (conversation) {
        conversation.unseen_count = 0;
      }
    },
    removeArchiveChatById(state, action: PayloadAction<number>) {
      const chatIdToRemove = action.payload;

      // Find chat index by chat_id
      const chatIndex = state.Chats.findIndex(
        (chat: OuterChat) => chat.Records[0].chat_id === chatIdToRemove,
      );

      // If chat exists, remove it from the array
      if (chatIndex !== -1) {
        state.Chats.splice(chatIndex, 1);
      }
    },
    addToArchiveList(state, action: PayloadAction<{ chat: OuterChat }>) {
      state.Chats = insertChatSorted(state.Chats, action.payload.chat);
    },
  },
});

// Export the reducer and actions
export default ArchiveListSlice.reducer;
export const {
  updateArchiveList,
  updateArchiveListByChatId,
  updateArchiveListForNewMessage,
  updateArchiveListUnreadCountByChatId,
  removeArchiveChatById,
  addToArchiveList,
} = ArchiveListSlice.actions;
