import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import {
  Message,
  MessageList,
  MessageListRes,
} from "../../types/MessageListType";
import { SingleMessageRes } from "../../types/SingleMessageType";
import insertDateDividers from "../../utils/insertDateDividers";

// Define the initial state with an empty MessageList
const initialState: MessageListRes = {
  message_list: {
    Records: [],
    Pagination: {
      total_pages: 0,
      total_records: 0,
      current_page: 0,
      records_per_page: 0,
    },
  },
  pinned_messages: {
    Records: [],
    Pagination: {
      total_pages: 0,
      total_records: 0,
      current_page: 0,
      records_per_page: 0,
    },
  },
};

// Create a slice of the state
const MessageListSlice = createSlice({
  name: "MessageList",
  initialState,
  reducers: {
    // Reducer to update the MessageList
    updateMessageList(state, action: PayloadAction<MessageListRes>) {
      const incomingRecords = action.payload.message_list.Records;

      if (
        state.message_list.Records.length === 0 ||
        incomingRecords.length === 0 ||
        state.message_list.Records[0]?.chat_id !== incomingRecords[0]?.chat_id
      ) {
        const merged = [...incomingRecords].reverse();
        return {
          ...action.payload,
          message_list: {
            ...action.payload.message_list,
            Records: insertDateDividers(merged),
          },
        };
      }

      const existingMessageIds = new Set(
        state.message_list.Records.map((msg) => msg.message_id),
      );

      const newMessages = incomingRecords.filter(
        (msg) => !existingMessageIds.has(msg.message_id),
      );

      const merged = [...newMessages]
        .reverse()
        .concat(state.message_list.Records);
      const cleaned = merged.filter(
        (msg, index, arr) => (msg.message_type === "date" ? false : true), // remove existing date types before re-inserting
      );

      return {
        ...action.payload,
        message_list: {
          ...action.payload.message_list,
          Records: insertDateDividers(cleaned),
        },
      };
    },

    removeMessageList() {
      return initialState; //Remove Data from messagelist when user click on ther conversations from chatlist
    },
    removeMessagesByIds(state, action: PayloadAction<number[]>) {
      state.message_list.Records = state.message_list.Records.filter(
        (message) => !action.payload.includes(message.message_id),
      );
    },
    removePinnedMessagesByIds(state, action: PayloadAction<number[]>) {
      state.pinned_messages.Records = state.pinned_messages.Records.filter(
        (message) => !action.payload.includes(message.message_id),
      );
    },
    appendMessage(state, action: PayloadAction<SingleMessageRes>) {
      state.message_list.Records.push(action.payload.Records[0]);
    },
    // Reducer to append a single object with date check
    appendMessageWithDateCheck(state, action: PayloadAction<Message>) {
      state.message_list.Records.push(action.payload);
    },

    // updatePollVote(
    //   state,
    //   action: PayloadAction<{
    //     message_id: number;
    //     user_id: number;
    //     new_option_id: number;
    //   }>,
    // ) {
    //   const { message_id, user_id, new_option_id } = action.payload;

    //   return state.map((message) => {
    //     if (message.message_list.Records[0].message_id !== message_id)
    //       return message;

    //     return {
    //       ...message,
    //       pollData: message.pollData.map((pollOption) => {
    //         const pollOptionData = JSON.parse(JSON.stringify(pollOption)); // Deep copy
    //         // console.log(pollOptionData, "pollOption");

    //         return {
    //           ...pollOptionData,
    //           PollVotes:
    //             pollOptionData.poll_option_id === new_option_id
    //               ? [
    //                   ...pollOptionData.PollVotes,
    //                   { user_id, updatedAt: new Date().toISOString() },
    //                 ]
    //               : pollOptionData.PollVotes.filter(
    //                   (vote: PollVote) => vote.user_id !== user_id,
    //                 ),
    //         };
    //       }),
    //     };
    //   });
    // },

    // Reducer to update the is_star_message field by message_id
    appendPinnedMessages(state, action: PayloadAction<Message>) {
      state.pinned_messages.Records.push(action.payload);
    },
    updateMessagesByIds(
      state,
      action: PayloadAction<{
        message_id: number;
        message?: string;
        delete_from_everyone?: boolean;
        user_id?: string;
        pinned?: boolean;
        message_seen_status?: "seen" | "sent";
      }>,
    ) {
      const msg = state.message_list.Records.find(
        (m) => m.message_id === action.payload.message_id,
      );

      if (msg) {
        msg.message_content = action.payload.message || msg.message_content;
        msg.deleted_for_everyone =
          action.payload.delete_from_everyone || msg.deleted_for_everyone;
        msg.pinned = action.payload.pinned || msg.pinned;
        msg.message_seen_status =
          action.payload.message_seen_status || msg.message_seen_status;
      }
    },

    updateIsStarMessage(
      state,
      action: PayloadAction<{ message_id: number; is_star_message: boolean }>,
    ) {
      const { message_id, is_star_message } = action.payload;
      const message = state.message_list.Records.find(
        (msg) => msg.message_id == message_id,
      );

      if (message) {
        message.starred = is_star_message;
      }
    },
  },
});

// Export the reducer and actions
export default MessageListSlice.reducer;
export const {
  updateMessageList,
  removeMessagesByIds,
  appendMessage,
  removePinnedMessagesByIds,
  appendMessageWithDateCheck,
  removeMessageList,
  updateIsStarMessage,
  updateMessagesByIds,
  appendPinnedMessages
  // updatePollVote,
} = MessageListSlice.actions;
