import { create } from "zustand";
import { immer } from "zustand/middleware/immer";

interface CommentStore {
  comments: CommentsSchema;

  // Comment operations
  addComment: (comment: CommentSchema) => void;
  setComments: (comments: CommentsSchema) => void;
  updateComment: (threadId: string, updates: Partial<CommentSchema>) => void;
  removeComment: (threadId: string) => void;

  // Reply operations
  addReply: (threadId: string, reply: Reply) => void;
  updateReply: (
    threadId: string,
    replyId: string,
    updates: Partial<Reply>
  ) => void;
  removeReply: (threadId: string, _id: string) => void;

  // Getters
  getCommentById: (threadId: string) => CommentSchema | undefined;
}

export const useCommentStore = create<CommentStore>()(
  immer((set, get) => ({
    comments: [],

    // Comment operations
    addComment: (comment) => {
      set((state) => {
        if (!state.comments.find((c) => c.threadId === comment.threadId)) {
          state.comments.push(JSON.parse(JSON.stringify(comment)));
        }
      });
    },

    setComments: (comments) => {
      set((state) => {
        state.comments = comments;
      });
    },

    updateComment: (threadId, updates) => {
      console.log("threadId:updater ", threadId);
      set((state) => {
        const comment = state.comments.find((c) => c.threadId === threadId);
        if (comment) {
          Object.assign(comment, updates);
        }
      });
    },

    removeComment: (threadId) => {
      set((state) => {
        state.comments = state.comments.filter((c) => c.threadId !== threadId);
      });
    },

    // Reply operations
    addReply: (threadId, comment) => {
      set((state) => {
        const reply = state.comments.find((c) => c.threadId === threadId);
        if (reply) {
          reply.comments.push(comment);
        }
      });
    },

    updateReply: (threadId, replyId, updates) => {
      set((state) => {
        const reply = state.comments.find((c) => c.threadId === threadId);
        if (reply) {
          const comment = reply.comments.find((r) => r.replyId === replyId);
          if (comment) {
            Object.assign(comment, updates);
          }
        }
      });
    },

    removeReply: (threadId, _id) => {
      set((state) => {
        const comment = state.comments.find((c) => c.threadId === threadId);
        if (comment) {
          comment.comments = comment.comments.filter((r) => r.replyId !== _id);
        }
      });
    },

    // Getter
    getCommentById: (threadId) => {
      return get().comments.find((c) => c.threadId === threadId);
    },
  }))
);
