import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import {
  ChatListRes,
  Message,
  OuterChat,
  PeerUserData,
} from "../../types/ChatListType";
import { Chat } from "../../types/SingleMessageType";
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 ChatListSlice = createSlice({
  name: "chatList",
  initialState,
  reducers: {
    // Reducer to update the chatList
    updateChatList(state, action: PayloadAction<ChatListRes>) {
      // console.log("action.payload", action.payload);
      // Directly modify the state to replace the chatList
      return action.payload;
    },
    updateByChatId(
      state,
      action: PayloadAction<{
        chat_id?: number;
        last_message?: string;
        last_message_type?: string;
        blocked_by?: string[];
        group_icon?: string;
        group_name?: string;
        Messages?: Message;
        cleared_for?: string[];
      }>,
    ) {
      console.log(action.payload, "action.payload");
      const chatRecords = state.Chats;
      console.log(chatRecords, "chatRecords");
      if (!chatRecords) return;

      const conversation = chatRecords.find(
        (c) => c.Records[0].chat_id == action.payload.chat_id,
      );

      if (conversation && conversation.Records[0].Messages.length > 0) {
        conversation.Records[0].Messages[0].message_content =
          action.payload.last_message ??
          conversation.Records[0].Messages[0].message_content;
        conversation.Records[0].Messages[0].message_type =
          action.payload.last_message_type ??
          conversation.Records[0].Messages[0].message_type;
        conversation.Records[0].Messages[0].updatedAt =
          new Date() ?? conversation.Records[0].Messages[0].updatedAt;
        conversation.Records[0].blocked_by =
          action.payload.blocked_by ?? conversation.Records[0].blocked_by;
        conversation.Records[0].group_icon =
          action.payload.group_icon ?? conversation.Records[0].group_icon;
        conversation.Records[0].group_name =
          action.payload.group_name ?? conversation.Records[0].group_name;
        conversation.Records[0].Messages =
          action.payload.Messages ?? conversation.Records[0].Messages;
        conversation.Records[0].cleared_for =
          action.payload.cleared_for ?? conversation.Records[0].cleared_for;
      }
    },
    updateChatListForNewMessage(
      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
        Chat?: Chat;
        cleared_for?: string[];
        unseen_count?: number;
      }>,
    ) {
      const {
        chat_id,
        last_message,
        last_message_type,
        peerUserData,
        createdAt,
        cleared_for,
        unseen_count,
      } = 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: action.payload.Chat?.chat_type || "private", // or "group" - depends on your logic
              group_name: action.payload.Chat?.group_name || "",
              group_icon: action.payload.Chat?.group_icon || "",
              group_description: action.payload.Chat?.group_description || "",
              deleted_at: action.payload.Chat?.deleted_at || null,
              is_group_blocked: action.payload.Chat?.is_group_blocked || false,
              createdAt: createdAt || new Date(),
              updatedAt: new Date(),
              deletedAt: action.payload.Chat?.deletedAt || null,
              cleared_for: [],
              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: unseen_count || 0,
            },
          ],
          PeerUserData: peerUserData!,
        };

        // Insert new chat at top
        state.Chats.unshift(newChat);
      }
    },
    updateUnreadCountByChatId(
      state,
      action: PayloadAction<{
        chat_id: number;
        mode: "reset" | "increment"; // define operation mode
      }>,
    ) {
      const conversation = state.Chats.find(
        (conv) => conv.Records[0].chat_id == action.payload.chat_id,
      );
      console.log(conversation, "conversation");

      if (conversation) {
        if (action.payload.mode === "reset") {
          conversation.Records[0].unseen_count = 0;
        } else if (action.payload.mode === "increment") {
          conversation.Records[0].unseen_count += 1;
        }
      }
    },
    addToChatList(state, action: PayloadAction<{ chat: OuterChat }>) {
      state.Chats = insertChatSorted(state.Chats, action.payload.chat);
    },
    removeChatById(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);
      }
    },
  },
});

// Export the reducer and actions
export default ChatListSlice.reducer;
export const {
  updateChatList,
  updateByChatId,
  updateChatListForNewMessage,
  updateUnreadCountByChatId,
  removeChatById,
  addToChatList,
} = ChatListSlice.actions;
