import { create } from "zustand";
import { ChatMessage, ProposedEventChange } from "@calchat/shared";

type BubbleSide = "left" | "right";

export type MessageData = {
  id: string;
  side: BubbleSide;
  content: string;
  proposedChanges?: ProposedEventChange[];
  conversationId?: string;
};

interface ChatState {
  messages: MessageData[];
  isWaitingForResponse: boolean;
  addMessages: (messages: MessageData[]) => void;
  addMessage: (message: MessageData) => void;
  updateMessage: (id: string, updates: Partial<MessageData>) => void;
  clearMessages: () => void;
  setWaitingForResponse: (waiting: boolean) => void;
}

export const useChatStore = create<ChatState>((set) => ({
  messages: [],
  isWaitingForResponse: false,
  addMessages(messages) {
    set((state) => ({ messages: [...state.messages, ...messages] }));
  },
  addMessage: (message: MessageData) => {
    set((state) => ({ messages: [...state.messages, message] }));
  },
  updateMessage: (id: string, updates: Partial<MessageData>) => {
    set((state) => ({
      messages: state.messages.map((msg) =>
        msg.id === id ? { ...msg, ...updates } : msg,
      ),
    }));
  },
  clearMessages: () => {
    set({ messages: [] });
  },
  setWaitingForResponse: (waiting: boolean) => {
    set({ isWaitingForResponse: waiting });
  },
}));

// Helper to convert server ChatMessage to client MessageData
export function chatMessageToMessageData(msg: ChatMessage): MessageData {
  return {
    id: msg.id,
    side: msg.sender === "assistant" ? "left" : "right",
    content: msg.content,
    proposedChanges: msg.proposedChanges,
    conversationId: msg.conversationId,
  };
}
