File size: 8,240 Bytes
57f5158
8c762ac
4bae792
 
8c762ac
 
 
 
4bae792
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c47e22
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c762ac
 
 
 
 
 
 
 
 
4bae792
 
 
 
8c762ac
57f5158
4c47e22
 
57f5158
8c762ac
4bae792
 
 
 
8c762ac
4bae792
57f5158
 
 
4c47e22
57f5158
 
8c762ac
57f5158
 
 
 
 
 
4bae792
8c762ac
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c762ac
 
 
4bae792
 
 
 
 
8c762ac
 
 
 
 
 
 
 
 
 
 
4c47e22
8c762ac
 
 
 
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4bf04d
4bae792
57f5158
 
 
 
 
 
 
 
 
 
 
b4bf04d
 
57f5158
 
 
b4bf04d
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
8c762ac
 
4bae792
8c762ac
4bae792
 
 
8c762ac
 
 
 
 
 
 
4bae792
 
 
 
 
 
8c762ac
4bae792
 
 
 
8c762ac
4bae792
 
 
 
 
 
 
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
import { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { dmService } from "../services/dm.service";
import socketService from "../services/socket.service";
import {
  updateUserStatus,
  updateUserProfile,
} from "../store/slices/dmSlice";

// Format relative time for DM list
function formatRelativeTime(dateStr) {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return "";

  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);

  if (diffSec < 60) return "Vừa xong";
  if (diffMin < 60) return `${diffMin} phút`;
  if (diffHour < 24) return `${diffHour} giờ`;

  const isYesterday =
    now.getDate() - date.getDate() === 1 &&
    now.getMonth() === date.getMonth() &&
    now.getFullYear() === date.getFullYear();
  if (isYesterday) return "Hôm qua";

  return `${String(date.getDate()).padStart(2, "0")}/${String(date.getMonth() + 1).padStart(2, "0")}`;
}

const CONVERSATIONS_CACHE_TTL = 5 * 60 * 1000; // 5 minutes

const STUDYBOT = {
  id: "studybot",
  userId: "studybot",
  name: "StudyBot",
  avatar: "🤖",
  lastMessage: "",
  hasNewMessage: false,
  unreadCount: 0,
  isBot: true,
  email: "studybot@vinclassroom.edu.vn",
  bio: "Trợ lý AI học tập của bạn",
};

function matchesStudyBot(query) {
  if (!query) return false;
  const q = query.toLowerCase();
  const keywords = [
    "studybot",
    "trợ lý",
    "trợ ly",
    "ai",
    "bot",
    "học tập",
    "study",
  ];
  return keywords.some((k) => q.includes(k));
}

export function useDMList() {
  const dispatch = useDispatch();
  const { conversations, onlineUsers, conversationsFetched, messages: messagesMap } = useSelector(
    (state) => state.dm,
  );
  const currentUserId = useSelector((state) => state.auth.user?.id);

  const [searchResults, setSearchResults] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState(null);
  const [onlineStatus, setOnlineStatus] = useState({}); // { [userId]: { online, lastSeen } }

  // Conversations are now fetched globally in App.jsx after auth
  // This hook only reads from Redux store, no need to fetch here
  // Background refresh is handled by App.jsx to avoid duplicate requests

  // Online status now handled globally in App.jsx via Redux
  // This effect only syncs from Redux to local state for DMList
  useEffect(() => {
    const next = {};
    onlineUsers.forEach((uid) => {
      next[uid] = { online: true, lastSeen: null };
    });
    setOnlineStatus(next);
  }, [onlineUsers]);

  // Search users via API
  useEffect(() => {
    if (!searchQuery.trim()) {
      setSearchResults([]);
      setIsSearching(false);
      return;
    }

    let mounted = true;

    const doSearch = async () => {
      try {
        setSearchResults([]);
        setIsSearching(true);
        const { data } = await dmService.searchUsers(searchQuery.trim());
        if (!mounted) return;

        let normalized = (data.users || []).map((user) => ({
          id: user.id,
          userId: user.id,
          name: user.display_name || user.email || "Unknown",
          avatar: user.avatar_url || null,
          color: user.color || null,
          lastMessage: "",
          hasNewMessage: false,
          unreadCount: 0,
          isBot: false,
          email: user.email || "",
          bio: user.bio || "",
        }));

        if (matchesStudyBot(searchQuery)) {
          const hasStudyBot = normalized.some(
            (u) => u.userId === STUDYBOT.userId,
          );
          if (!hasStudyBot) {
            normalized = [STUDYBOT, ...normalized];
          }
        }

        // Update Redux store with user profile info (including color)
        normalized.forEach((user) => {
          if (user.color) {
            dispatch(
              updateUserProfile({
                userId: user.userId,
                updates: {
                  color: user.color,
                  display_name: user.name,
                  avatar_url: user.avatar,
                },
              }),
            );
          }
        });

        setSearchResults(normalized);
      } catch (err) {
        if (mounted) {
          if (matchesStudyBot(searchQuery)) {
            setSearchResults([STUDYBOT]);
          } else {
            setSearchResults([]);
          }
        }
      } finally {
        if (mounted) setIsSearching(false);
      }
    };

    doSearch();

    return () => {
      mounted = false;
    };
  }, [searchQuery, dispatch]);

  // Helper: get latest message timestamp from Redux messages
  const getLatestMessageTime = (conversationId) => {
    const msgs = messagesMap[conversationId];
    if (!msgs || msgs.length === 0) return null;
    return [...msgs].reduce((latest, m) => {
      const t = m.created_at ? new Date(m.created_at).getTime() : 0;
      return t > latest ? t : latest;
    }, 0);
  };

  // Normalize conversations for UI and sort by latest message timestamp
  const normalizedConversations = [...conversations]
    .sort((a, b) => {
      const timeA = getLatestMessageTime(a.id) || (a.last_message?.created_at ? new Date(a.last_message.created_at).getTime() : 0);
      const timeB = getLatestMessageTime(b.id) || (b.last_message?.created_at ? new Date(b.last_message.created_at).getTime() : 0);
      return timeB - timeA; // newest first
    })
    .map((conv) => {
      // Get latest message from Redux (sorted by created_at)
      const msgs = messagesMap[conv.id];
      let latestMsg = null;
      if (msgs && msgs.length > 0) {
        latestMsg = [...msgs].sort((m1, m2) => {
          const t1 = m1.created_at ? new Date(m1.created_at).getTime() : 0;
          const t2 = m2.created_at ? new Date(m2.created_at).getTime() : 0;
          return t2 - t1;
        })[0];
      }
      const apiLastMsg = conv.last_message;
      const msgToShow = latestMsg || apiLastMsg;

      const isOwn = msgToShow?.sender_id && currentUserId && String(msgToShow.sender_id) === String(currentUserId);
      const prefix = isOwn ? "Bạn: " : "";
      const content = msgToShow?.content || "";
      const lastMessageText = content ? `${prefix}${content}` : (conv.isBot ? "Trợ lý AI" : "Bắt đầu trò chuyện");

      const timeStr = formatRelativeTime(msgToShow?.created_at || msgToShow?.timestamp);

      return {
        id: conv.id,
        userId: conv.other_user?.id,
        name: conv.other_user?.display_name || "Unknown",
        avatar: conv.other_user?.avatar_url || null,
        color: conv.other_user?.color || null,
        lastMessage: lastMessageText,
        lastMessageTime: timeStr,
        hasNewMessage: (conv.unread_count || 0) > 0,
        unreadCount: conv.unread_count || 0,
        isBot: false,
        email: conv.other_user?.email || "",
        mutualFriends: 0,
        conversation: conv,
      };
    });

  const filteredConversations = searchQuery.trim()
    ? normalizedConversations.filter((dm) =>
        dm.name.toLowerCase().includes(searchQuery.toLowerCase()),
      )
    : normalizedConversations;

  const globalSearchResults = searchQuery.trim()
    ? searchResults.map((user) => {
        const existing = normalizedConversations.find(
          (c) => c.userId === user.userId,
        );
        // Merge: prefer search result data (has color) but keep conversation data if available
        return existing
          ? { ...user, ...existing, color: user.color || existing.color }
          : user;
      })
    : [];

  const isSearchingActive = searchQuery.trim().length > 0;

  return {
    conversations: normalizedConversations,
    items: isSearchingActive ? globalSearchResults : filteredConversations,
    onlineStatus,
    searchQuery,
    setSearchQuery,
    isLoading: false, // handled by Redux
    isSearching,
    error,
    isSearchingActive,
    getUserOnlineStatus: (userId) =>
      onlineStatus[userId] || { online: false, lastSeen: null },
  };
}