File size: 14,747 Bytes
149698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc415a
149698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc415a
149698e
 
efc415a
149698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { ScanLine, StopCircle, CheckCircle2, AlertTriangle } from 'lucide-react';
import { useEmailScan } from '@/hooks/useEmailScan';
import { useScanEvents } from '@/hooks/useRealtime';
import type { ScanPreset } from '@icc/shared';

interface LogEntry {
  id: string;
  time: string;
  type: 'found' | 'duplicate' | 'info' | 'error';
  sender?: string;
  amount?: string;
  ref?: string;
  branch?: string;
  message?: string;
}

interface ScanModalProps {
  onClose: () => void;
  onMinimize: () => void;
  preset?: ScanPreset;
  forceRescan?: boolean;
  startDate?: string;
  endDate?: string;
}

function formatTime(date?: Date): string {
  const d = date ?? new Date();
  return d.toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

export default function ScanModal({ onClose, onMinimize, preset = 'today', forceRescan = false, startDate, endDate }: ScanModalProps) {
  const { t } = useTranslation();
  const { startScan, activeJobId, scanStatus, scanError, isStarting } = useEmailScan();
  const [logEntries, setLogEntries] = useState<LogEntry[]>([]);
  const [stats, setStats] = useState({ processed: 0, skipped: 0, errored: 0, total: 0 });
  const [status, setStatus] = useState<'starting' | 'scanning' | 'completed' | 'failed'>('starting');
  const [dateRange, setDateRange] = useState<{ startDate?: string; endDate?: string }>({});
  const logContainerRef = useRef<HTMLDivElement>(null);
  const scanStarted = useRef(false);

  // Start scan on mount
  useEffect(() => {
    if (scanStarted.current) return;
    scanStarted.current = true;
    startScan(preset, { forceRescan, startDate, endDate });
  }, [preset, forceRescan, startScan]);

  // Add log entry helper
  const addLog = useCallback((entry: Omit<LogEntry, 'id'>) => {
    setLogEntries(prev => {
      const newEntries = [{ ...entry, id: `${Date.now()}_${Math.random().toString(36).slice(2)}` }, ...prev];
      return newEntries.slice(0, 50);
    });
  }, []);

  // Listen to WebSocket events
  useScanEvents({
    onStarted: useCallback((data: any) => {
      setStatus('scanning');
      setStats(prev => ({ ...prev, total: data.newEmails ?? 0, skipped: data.skipped ?? 0 }));
      setDateRange({ startDate: data.dateRange?.startDate, endDate: data.dateRange?.endDate });
      addLog({
        time: formatTime(),
        type: 'info',
        message: `${data.totalEmails ?? 0} ${t('scanModal.logEmailsFound')}, ${data.newEmails ?? 0} ${t('scanModal.logNewToProcess')}`,
      });
      if (data.skipped > 0) {
        addLog({
          time: formatTime(),
          type: 'duplicate',
          message: `${data.skipped} ${t('scanModal.logAlreadyProcessed')}`,
        });
      }
    }, [addLog, t]),

    onProgress: useCallback((data: any) => {
      setStatus('scanning');
      setStats({
        processed: data.processed ?? 0,
        total: data.total ?? 0,
        skipped: data.skipped ?? 0,
        errored: data.errored ?? 0,
      });

      if (data.latest) {
        const tx = data.latest;
        addLog({
          time: formatTime(),
          type: 'found',
          sender: tx.sender || 'Inconnu',
          amount: tx.amount ? `${Number(tx.amount).toFixed(2)}$` : undefined,
          ref: tx.reference,
          branch: tx.branch,
        });
      }

      if (data.error) {
        addLog({
          time: formatTime(),
          type: 'error',
          message: data.error.message || 'Erreur de traitement',
        });
      }
    }, [addLog]),

    onCompleted: useCallback((data: any) => {
      setStatus('completed');
      addLog({
        time: formatTime(),
        type: 'info',
        message: `${t('scanModal.logScanComplete')} (${data.duration ?? ''}) — ${data.summary?.parsed ?? 0} ${t('scanModal.logTransactionsExtracted')}`,
      });
    }, [addLog, t]),

    onError: useCallback((data: any) => {
      setStatus('failed');
      addLog({
        time: formatTime(),
        type: 'error',
        message: data.message || t('scanModal.logScanError'),
      });
    }, [addLog, t]),
  });

  // Also update from polling status (fallback)
  useEffect(() => {
    if (scanStatus) {
      if (scanStatus.status === 'completed') setStatus('completed');
      if (scanStatus.status === 'failed') setStatus('failed');
      if (scanStatus.status === 'scanning' || scanStatus.status === 'parsing') setStatus('scanning');
    }
  }, [scanStatus]);

  // Track error from mutation
  useEffect(() => {
    if (scanError) {
      setStatus('failed');
      addLog({ time: formatTime(), type: 'error', message: scanError.message });
    }
  }, [scanError, addLog]);

  const emailsDone = stats.processed + stats.errored;
  const progressPercent = stats.total > 0
    ? Math.round((emailsDone / stats.total) * 100)
    : 0;

  const totalProcessed = emailsDone + stats.skipped;
  const grandTotal = stats.total + stats.skipped;
  const totalPercent = grandTotal > 0
    ? Math.round((totalProcessed / grandTotal) * 100)
    : 0;

  const isActive = status === 'starting' || status === 'scanning';

  return (
    <div className="absolute inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4">
      <div className="w-full max-w-2xl transform overflow-hidden rounded-2xl bg-white p-8 text-left shadow-2xl border border-white/20">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <div className="relative flex h-12 w-12 items-center justify-center rounded-xl bg-blue-50 text-primary">
              {status === 'completed' ? (
                <CheckCircle2 className="h-7 w-7 text-emerald-600" />
              ) : status === 'failed' ? (
                <AlertTriangle className="h-7 w-7 text-red-600" />
              ) : (
                <ScanLine className="h-7 w-7 animate-pulse" />
              )}
              {isActive && (
                <div className="absolute -right-1 -top-1 h-3 w-3 rounded-full bg-green-500 ring-2 ring-white" />
              )}
            </div>
            <div>
              <h3 className="text-xl font-bold text-slate-900">
                {status === 'completed' ? t('scanModal.titleComplete') : status === 'failed' ? t('scanModal.titleError') : t('scanModal.title')}
              </h3>
              <p className="text-sm text-slate-500 flex items-center gap-1.5">
                {isActive && <span className="h-1.5 w-1.5 rounded-full bg-green-500 animate-pulse" />}
                {t('scanModal.engine', 'Scan Engine active')}
              </p>
            </div>
          </div>
          {activeJobId && (
            <div className="rounded-lg bg-slate-50 px-3 py-1.5 text-xs font-medium text-slate-600 border border-slate-100">
              {t('scanModal.sessionId')}: #{activeJobId.slice(-8).toUpperCase()}
            </div>
          )}
        </div>

        {/* Progress section */}
        <div className="mb-8 space-y-6">
          <div className="flex justify-between items-end text-sm mb-2">
            <span className="font-semibold text-slate-900">
              {isStarting ? t('scanModal.starting') : `${emailsDone} / ${stats.total} ${t('scanModal.emailsLabel')}`}
            </span>
            {dateRange.startDate && dateRange.endDate && (
              <span className="text-slate-500">
                {t('scanModal.processing')} {dateRange.startDate.slice(0, 10)} {t('scanModal.toDate')} {dateRange.endDate.slice(0, 10)}
              </span>
            )}
          </div>

          <div className="space-y-4">
            {/* Current progress */}
            <div>
              <div className="flex justify-between text-xs mb-1.5">
                <span className="text-slate-600 font-medium">{t('scanModal.batchProgress')}</span>
                <span className="text-primary font-bold">{progressPercent}%</span>
              </div>
              <div className="h-2.5 w-full rounded-full bg-slate-100 overflow-hidden">
                <div
                  className="h-full rounded-full bg-primary transition-all duration-500 ease-out relative overflow-hidden"
                  style={{ width: `${progressPercent}%` }}
                >
                  {isActive && <div className="absolute inset-0 bg-white/20 animate-pulse" />}
                </div>
              </div>
            </div>

            {/* Total progress */}
            <div>
              <div className="flex justify-between text-xs mb-1.5">
                <span className="text-slate-500">{t('scanModal.totalProgress')}</span>
                <span className="text-slate-700 font-semibold">{totalPercent}%</span>
              </div>
              <div className="h-1.5 w-full rounded-full bg-slate-100">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    status === 'completed' ? 'bg-emerald-500' : status === 'failed' ? 'bg-red-400' : 'bg-slate-400/60'
                  }`}
                  style={{ width: `${totalPercent}%` }}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Stats grid */}
        <div className="grid grid-cols-3 gap-4 mb-8">
          <div className="rounded-xl bg-slate-50 p-4 border border-slate-100">
            <div className="text-slate-500 text-xs font-medium mb-1 uppercase tracking-wide">{t('scanModal.emailsAnalyzed')}</div>
            <div className="text-2xl font-bold text-slate-900">{stats.processed}</div>
          </div>
          <div className="rounded-xl bg-slate-50 p-4 border border-slate-100">
            <div className="text-slate-500 text-xs font-medium mb-1 uppercase tracking-wide">{t('scanModal.duplicatesSkipped')}</div>
            <div className="text-2xl font-bold text-slate-700">{stats.skipped}</div>
          </div>
          <div className={`rounded-xl p-4 border ${stats.errored > 0 ? 'bg-red-50 border-red-100' : 'bg-slate-50 border-slate-100'}`}>
            <div className={`text-xs font-medium mb-1 uppercase tracking-wide ${stats.errored > 0 ? 'text-red-600' : 'text-slate-500'}`}>
              {t('scanModal.errors')}
            </div>
            <div className={`text-2xl font-bold ${stats.errored > 0 ? 'text-red-700' : 'text-slate-700'}`}>{stats.errored}</div>
          </div>
        </div>

        {/* Extraction log */}
        <div className="mb-8 rounded-xl border border-slate-200 bg-slate-50 overflow-hidden">
          <div className="border-b border-slate-200 bg-slate-100/50 px-4 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wider flex justify-between items-center">
            <span>{t('scanModal.extractionLog', 'Extraction Log')}</span>
            {isActive && <span className="h-1.5 w-1.5 rounded-full bg-green-500 animate-pulse" />}
          </div>
          <div ref={logContainerRef} className="h-40 overflow-y-auto p-4 space-y-2 font-mono text-sm">
            {logEntries.length === 0 ? (
              <div className="flex items-center justify-center h-full text-slate-400 text-xs">
                {isStarting ? t('scanModal.logWaiting') : t('scanModal.logEmpty')}
              </div>
            ) : (
              logEntries.map((entry, index) => (
                <div key={entry.id} className="flex items-start gap-3" style={{ opacity: Math.max(0.4, 1 - index * 0.08) }}>
                  <span className="text-slate-400 text-xs mt-0.5">{entry.time}</span>
                  <div className="flex-1">
                    {entry.type === 'found' && (
                      <>
                        <span className="text-emerald-600 font-semibold">{t('scanModal.logFound')}:</span>{' '}
                        <span className="text-slate-800">{entry.sender}</span>
                        {entry.amount && (
                          <>
                            <span className="mx-2 text-slate-300">|</span>
                            <span className="text-slate-600">{t('scanModal.logAmount')}:</span>{' '}
                            <span className="text-slate-900 font-bold">{entry.amount}</span>
                          </>
                        )}
                        {entry.ref && (
                          <>
                            <span className="mx-2 text-slate-300">|</span>
                            <span className="text-slate-500 text-xs">Ref: {entry.ref}</span>
                          </>
                        )}
                      </>
                    )}
                    {entry.type === 'duplicate' && (
                      <>
                        <span className="text-amber-600 font-semibold">{t('scanModal.logDuplicate')}:</span>{' '}
                        <span className="text-slate-600">{entry.message}</span>
                      </>
                    )}
                    {entry.type === 'info' && (
                      <span className="text-slate-500">{entry.message}</span>
                    )}
                    {entry.type === 'error' && (
                      <>
                        <span className="text-red-600 font-semibold">{t('scanModal.logError')}:</span>{' '}
                        <span className="text-red-700">{entry.message}</span>
                      </>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Action buttons */}
        <div className="flex justify-end gap-3">
          <button
            onClick={onMinimize}
            className="rounded-lg bg-white px-5 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-800 border border-slate-200 shadow-sm transition-colors"
          >
            {t('scan.minimize')}
          </button>
          {status === 'completed' || status === 'failed' ? (
            <button
              onClick={onClose}
              className="group flex items-center gap-2 rounded-lg bg-primary px-6 py-2.5 text-sm font-semibold text-white hover:bg-primary/90 shadow-sm transition-all"
            >
              {t('common.close')}
            </button>
          ) : (
            <button
              onClick={onClose}
              className="group flex items-center gap-2 rounded-lg bg-red-50 px-6 py-2.5 text-sm font-semibold text-red-600 hover:bg-red-100 hover:shadow-sm border border-red-100 transition-all"
            >
              <StopCircle className="h-[18px] w-[18px] group-hover:scale-110 transition-transform" />
              {t('scanModal.stop')}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}