File size: 8,040 Bytes
2c6bb7b
590318c
2c6bb7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590318c
2c6bb7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590318c
2c6bb7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590318c
2c6bb7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { create } from 'zustand'
import { Chat, Message } from '../../../shared/types'
import { chatService } from '../services/chatService'

interface ChatState {
  chats: Chat[]
  currentChat: Chat | null
  messages: Record<string, Message[]>
  typingUsers: Record<string, string[]>
  onlineUsers: Set<string>
  loading: boolean
  error: string | null
}

interface ChatActions {
  // Chat management
  loadChats: () => Promise<void>
  selectChat: (chatId: string) => void
  createChat: (data: {

    type: 'direct' | 'group'

    name?: string

    participantIds: string[]

  }) => Promise<Chat>
  updateChat: (chatId: string, data: Partial<Chat>) => Promise<void>
  deleteChat: (chatId: string) => Promise<void>

  // Message management
  loadMessages: (chatId: string, page?: number) => Promise<void>
  sendMessage: (chatId: string, content: string, attachments?: File[]) => Promise<void>
  editMessage: (messageId: string, content: string) => Promise<void>
  deleteMessage: (messageId: string) => Promise<void>
  addReaction: (messageId: string, emoji: string) => Promise<void>
  removeReaction: (messageId: string, emoji: string) => Promise<void>

  // Real-time updates
  addMessage: (message: Message) => void
  updateMessage: (message: Message) => void
  removeMessage: (messageId: string) => void
  updateChatFromSocket: (chat: Chat) => void

  // Typing indicators
  setTyping: (chatId: string, userId: string, isTyping: boolean) => void
  
  // User status
  setUserOnline: (userId: string, isOnline: boolean) => void
  
  // Utility
  clearError: () => void
  reset: () => void
}

export const useChatStore = create<ChatState & ChatActions>((set, get) => ({
  // State
  chats: [],
  currentChat: null,
  messages: {},
  typingUsers: {},
  onlineUsers: new Set(),
  loading: false,
  error: null,

  // Actions
  loadChats: async () => {
    set({ loading: true, error: null })
    try {
      const chats = await chatService.getChats()
      set({ chats, loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
    }
  },

  selectChat: (chatId: string) => {
    const { chats } = get()
    const chat = chats.find(c => c.id === chatId)
    if (chat) {
      set({ currentChat: chat })
      // Load messages if not already loaded
      if (!get().messages[chatId]) {
        get().loadMessages(chatId)
      }
    }
  },

  createChat: async (data) => {
    set({ loading: true, error: null })
    try {
      const chat = await chatService.createChat(data)
      set(state => ({
        chats: [chat, ...state.chats],
        currentChat: chat,
        loading: false
      }))
      return chat
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  updateChat: async (chatId: string, data: Partial<Chat>) => {
    try {
      const updatedChat = await chatService.updateChat(chatId, data)
      set(state => ({
        chats: state.chats.map(chat => 
          chat.id === chatId ? updatedChat : chat
        ),
        currentChat: state.currentChat?.id === chatId ? updatedChat : state.currentChat
      }))
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  deleteChat: async (chatId: string) => {
    try {
      await chatService.deleteChat(chatId)
      set(state => ({
        chats: state.chats.filter(chat => chat.id !== chatId),
        currentChat: state.currentChat?.id === chatId ? null : state.currentChat,
        messages: Object.fromEntries(
          Object.entries(state.messages).filter(([id]) => id !== chatId)
        )
      }))
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  loadMessages: async (chatId: string, page = 1) => {
    set({ loading: true, error: null })
    try {
      const messages = await chatService.getMessages(chatId, page)
      set(state => ({
        messages: {
          ...state.messages,
          [chatId]: page === 1 ? messages : [...(state.messages[chatId] || []), ...messages]
        },
        loading: false
      }))
    } catch (error: any) {
      set({ error: error.message, loading: false })
    }
  },

  sendMessage: async (chatId: string, content: string, attachments?: File[]) => {
    try {
      await chatService.sendMessage(chatId, {
        content,
        type: 'text',
        attachments
      })
      // Message will be added via socket event
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  editMessage: async (messageId: string, content: string) => {
    try {
      await chatService.editMessage(messageId, content)
      // Message will be updated via socket event
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  deleteMessage: async (messageId: string) => {
    try {
      await chatService.deleteMessage(messageId)
      // Message will be removed via socket event
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  addReaction: async (messageId: string, emoji: string) => {
    try {
      await chatService.addReaction(messageId, emoji)
      // Reaction will be updated via socket event
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  removeReaction: async (messageId: string, emoji: string) => {
    try {
      await chatService.removeReaction(messageId, emoji)
      // Reaction will be updated via socket event
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  // Real-time updates
  addMessage: (message: Message) => {
    set(state => ({
      messages: {
        ...state.messages,
        [message.chatId]: [...(state.messages[message.chatId] || []), message]
      },
      chats: state.chats.map(chat => 
        chat.id === message.chatId 
          ? { ...chat, lastMessage: message, updatedAt: new Date() }
          : chat
      )
    }))
  },

  updateMessage: (message: Message) => {
    set(state => ({
      messages: {
        ...state.messages,
        [message.chatId]: (state.messages[message.chatId] || []).map(msg =>
          msg.id === message.id ? message : msg
        )
      }
    }))
  },

  removeMessage: (messageId: string) => {
    set(state => {
      const newMessages = { ...state.messages }
      Object.keys(newMessages).forEach(chatId => {
        newMessages[chatId] = newMessages[chatId].filter(msg => msg.id !== messageId)
      })
      return { messages: newMessages }
    })
  },

  updateChatFromSocket: (chat: Chat) => {
    set(state => ({
      chats: state.chats.map(c => c.id === chat.id ? chat : c),
      currentChat: state.currentChat?.id === chat.id ? chat : state.currentChat
    }))
  },

  setTyping: (chatId: string, userId: string, isTyping: boolean) => {
    set(state => {
      const typingUsers = { ...state.typingUsers }
      const currentTyping = typingUsers[chatId] || []
      
      if (isTyping) {
        if (!currentTyping.includes(userId)) {
          typingUsers[chatId] = [...currentTyping, userId]
        }
      } else {
        typingUsers[chatId] = currentTyping.filter(id => id !== userId)
        if (typingUsers[chatId].length === 0) {
          delete typingUsers[chatId]
        }
      }
      
      return { typingUsers }
    })
  },

  setUserOnline: (userId: string, isOnline: boolean) => {
    set(state => {
      const onlineUsers = new Set(state.onlineUsers)
      if (isOnline) {
        onlineUsers.add(userId)
      } else {
        onlineUsers.delete(userId)
      }
      return { onlineUsers }
    })
  },

  clearError: () => {
    set({ error: null })
  },

  reset: () => {
    set({
      chats: [],
      currentChat: null,
      messages: {},
      typingUsers: {},
      onlineUsers: new Set(),
      loading: false,
      error: null
    })
  }
}))