File size: 13,456 Bytes
766f889
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient } from "../lib/apiClient";
import { 
  Inbox as InboxIcon, 
  Search, 
  Send, 
  Sparkles, 
  CheckCircle2, 
  AlertCircle, 
  Clock, 
  Mail, 
  Calendar, 
  User, 
  Building, 
  ChevronRight, 
  Paperclip,
  Smile,
  RefreshCw
} from "lucide-react";
import { useState } from "react";
import DOMPurify from "dompurify";
import StatusBadge from "../components/StatusBadge";
import RichTextEditor from "../components/RichTextEditor";
import toast from "react-hot-toast";

const CATEGORIES = [
  { key: "ALL", label: "All Messages" },
  { key: "INTERESTED", label: "Interested" },
  { key: "MEETING_BOOKED", label: "Meeting Booked" },
  { key: "REPLIED", label: "Replied" },
  { key: "NOT_INTERESTED", label: "Not Interested" },
];

export default function Inbox() {
  const queryClient = useQueryClient();
  const [selectedCategory, setSelectedCategory] = useState("ALL");
  const [selectedMessageId, setSelectedMessageId] = useState<string | null>(null);
  const [replyBody, setReplyBody] = useState("");

  const { data: messages = [], isLoading, isError, refetch } = useQuery({
    queryKey: ["inbox-messages", selectedCategory],
    queryFn: async () => {
      const res = await apiClient.get("/inbox", {
        params: selectedCategory !== "ALL" ? { category: selectedCategory } : {},
      });
      return res.data;
    },
  });

  const selectedMessage = (Array.isArray(messages) ? messages : []).find((m: any) => m.id === selectedMessageId) || (Array.isArray(messages) ? messages[0] : null);

  const updateCategoryMutation = useMutation({
    mutationFn: async ({ messageId, category }: { messageId: string; category: string }) => {
      const res = await apiClient.post("/inbox/categorize", { thread_id: messageId, category });
      return res.data;
    },
    onSuccess: () => {
      toast.success("Lead categorization updated");
      queryClient.invalidateQueries({ queryKey: ["inbox-messages"] });
    },
    onError: () => {
      toast.error("Failed to update lead category");
    },
  });

  const sendReplyMutation = useMutation({
    mutationFn: async ({ campaignId, messageId, body }: { campaignId: string; messageId: string; body: string }) => {
      const res = await apiClient.post(`/campaigns/${campaignId}/reply-email-thread`, { thread_id: messageId, reply_body: body });
      return res.data;
    },
    onSuccess: () => {
      toast.success("Reply dispatched to lead");
      setReplyBody("");
      queryClient.invalidateQueries({ queryKey: ["inbox-messages"] });
    },
    onError: () => {
      toast.error("Failed to send reply");
    }
  });

  return (
    <div className="h-[calc(100vh-4rem)] flex flex-col overflow-hidden">
      {/* Top Controls */}
      <div className="h-14 border-b border-zinc-800 bg-zinc-950 px-6 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-3">
          <div className="p-1.5 bg-indigo-500/10 text-indigo-400 rounded-lg">
            <InboxIcon className="w-5 h-5" />
          </div>
          <div>
            <h1 className="text-base font-bold text-zinc-100 flex items-center gap-2">
              Unified Master Inbox
              <span className="text-[10px] font-bold uppercase tracking-wider bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2 py-0.5 rounded-full">
                AI Sentiment Active
              </span>
            </h1>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => refetch()}
            className="p-1.5 text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900 rounded-lg transition-colors"
            title="Refresh Inboxes"
          >
            <RefreshCw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 2-Pane Inbox Workspace */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left Pane: Message List */}
        <div className="w-80 md:w-96 border-r border-zinc-800 flex flex-col bg-zinc-950/60 shrink-0">
          {/* Categories Filter Tabs */}
          <div className="p-3 border-b border-zinc-800 flex gap-1 overflow-x-auto">
            {CATEGORIES.map((cat) => (
              <button
                key={cat.key}
                onClick={() => setSelectedCategory(cat.key)}
                className={`px-2.5 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors ${
                  selectedCategory === cat.key
                    ? "bg-indigo-600 text-white"
                    : "bg-zinc-900 text-zinc-400 hover:text-zinc-200"
                }`}
              >
                {cat.label}
              </button>
            ))}
          </div>

          {/* Messages Scroll Area */}
          <div className="flex-1 overflow-y-auto divide-y divide-zinc-800/60">
            {isLoading && (
              <div className="p-8 text-center text-xs text-zinc-400" role="status">Loading message threads…</div>
            )}

            {isError && (
              <div className="p-8 text-center text-xs text-rose-300" role="alert">Unable to load message threads.</div>
            )}

            {!isLoading && !isError && messages.map((msg: any) => {
              const isSelected = msg.id === selectedMessage?.id;
              return (
                <div
                  key={msg.id}
                  onClick={() => setSelectedMessageId(msg.id)}
                  onKeyDown={(event) => {
                    if (event.key === "Enter" || event.key === " ") setSelectedMessageId(msg.id);
                  }}
                  role="button"
                  tabIndex={0}
                  aria-pressed={isSelected}
                  className={`p-4 transition-colors cursor-pointer ${
                    isSelected ? "bg-indigo-950/30 border-l-2 border-indigo-500" : "hover:bg-zinc-900/40"
                  }`}
                >
                  <div className="flex items-start justify-between gap-2">
                    <span className="font-semibold text-xs text-zinc-100 truncate">
                      {msg.lead_name || msg.lead_email}
                    </span>
                    <span className="text-[10px] text-zinc-500 shrink-0">
                      {new Date(msg.received_at || Date.now()).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
                    </span>
                  </div>

                  <h4 className="text-xs font-medium text-zinc-300 mt-1 truncate">
                    {msg.subject}
                  </h4>

                  <p className="text-[11px] text-zinc-500 mt-1 line-clamp-2 leading-relaxed">
                    {msg.messages?.at(-1)?.body_html?.replace(/<[^>]*>?/gm, "") || "No message preview available"}
                  </p>

                  <div className="mt-2.5 flex items-center justify-between">
                    <StatusBadge status={msg.category || "REPLIED"} size="sm" />
                    <span className="text-[10px] text-zinc-400 font-mono">
                      {msg.company_name}
                    </span>
                  </div>
                </div>
              );
            })}

            {messages.length === 0 && (
              <div className="p-8 text-center text-xs text-zinc-500">
                No replies found for this category filter.
              </div>
            )}
          </div>
        </div>

        {/* Right Pane: Thread View & Response Composer */}
        {selectedMessage ? (
          <div className="flex-1 flex flex-col bg-zinc-950 overflow-hidden">
            {/* Thread Header */}
            <div className="p-5 border-b border-zinc-800 bg-zinc-900/30 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-full bg-indigo-600/20 text-indigo-400 flex items-center justify-center font-bold text-sm border border-indigo-500/30">
                  {selectedMessage.lead_name ? selectedMessage.lead_name[0] : "L"}
                </div>
                <div>
                  <h3 className="text-sm font-bold text-zinc-100 flex items-center gap-2">
                    {selectedMessage.subject}
                  </h3>
                  <div className="text-xs text-zinc-400 flex items-center gap-2 mt-0.5">
                    <span>{selectedMessage.lead_name} &lt;{selectedMessage.lead_email}&gt;</span>
                    <span>•</span>
                    <span className="font-mono text-zinc-500">{selectedMessage.company_name}</span>
                  </div>
                </div>
              </div>

              {/* Categorization Dropdown */}
              <div className="flex items-center gap-2">
                <span className="text-xs text-zinc-500">AI Intent:</span>
                <select
                  value={selectedMessage.category || "REPLIED"}
                  onChange={(e) =>
                    updateCategoryMutation.mutate({
                      messageId: selectedMessage.id,
                      category: e.target.value,
                    })
                  }
                  className="bg-zinc-900 border border-zinc-800 rounded-lg py-1.5 px-3 text-xs text-zinc-200 focus:outline-none focus:border-indigo-500"
                >
                  <option value="INTERESTED">Interested</option>
                  <option value="MEETING_BOOKED">Meeting Booked</option>
                  <option value="REPLIED">Replied</option>
                  <option value="NOT_INTERESTED">Not Interested</option>
                </select>
              </div>
            </div>

            {/* Conversation Messages */}
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
              {(selectedMessage.messages || []).map((message: any) => {
                const isInbound = message.direction === "INBOUND";
                return (
                  <div key={message.id} className={`max-w-2xl ${isInbound ? "ml-auto bg-indigo-950/40 border-indigo-500/30" : "bg-zinc-900 border-zinc-800"} border rounded-xl p-4 text-xs space-y-2`}>
                    <div className={`flex items-center justify-between ${isInbound ? "text-indigo-300 border-indigo-500/20" : "text-zinc-400 border-zinc-800"} pb-2 border-b`}>
                      <span className="font-semibold">{isInbound ? "Prospect reply" : "Outbound message"}</span>
                      <span className="text-[10px] text-zinc-400">{new Date(message.timestamp).toLocaleString()}</span>
                    </div>
                    <div
                      className="text-zinc-200 leading-relaxed prose prose-invert max-w-none text-xs"
                      dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(message.body_html || "") }}
                    />
                  </div>
                );
              })}
            </div>

            {/* Reply Composer Bottom Section */}
            <div className="p-4 border-t border-zinc-800 bg-zinc-950 shrink-0 space-y-3">
              <RichTextEditor
                content={replyBody}
                onChange={setReplyBody}
                placeholder="Compose your reply or insert calendar meeting booking link..."
              />

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => setReplyBody("<p>Hi, how does Tuesday at 2 PM EST work for a quick 15-min call? Here is my calendar: https://cal.com/alex/15min</p>")}
                    className="px-2.5 py-1 bg-zinc-900 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 border border-zinc-800 rounded-md text-[11px] transition-colors"
                  >
                    + Insert Booking Link
                  </button>
                  <button
                    type="button"
                    onClick={() => setReplyBody("<p>Thanks for getting back to me! I have attached our case study PDF here.</p>")}
                    className="px-2.5 py-1 bg-zinc-900 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 border border-zinc-800 rounded-md text-[11px] transition-colors"
                  >
                    + Insert Case Study
                  </button>
                </div>

                <button
                  type="button"
                  onClick={() => {
                    if (!replyBody) {
                      toast.error("Please write a reply message");
                      return;
                    }
                    sendReplyMutation.mutate({
                      campaignId: selectedMessage.campaign_id,
                      messageId: selectedMessage.id,
                      body: replyBody,
                    });
                  }}
                  className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-xs rounded-lg transition-colors flex items-center gap-2 shadow-md"
                >
                  <Send className="w-3.5 h-3.5" /> Send Reply
                </button>
              </div>
            </div>
          </div>
        ) : (
          <div className="flex-1 flex items-center justify-center text-xs text-zinc-500">
            Select a message thread from the left pane to view conversation.
          </div>
        )}
      </div>
    </div>
  );
}