File size: 13,469 Bytes
d084ead
 
fac0133
d084ead
 
fac0133
 
d084ead
 
 
 
 
 
 
 
 
 
fac0133
 
d084ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fac0133
 
 
 
d084ead
fac0133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d084ead
 
 
fac0133
d084ead
 
 
 
 
 
 
 
 
 
fac0133
d084ead
 
 
 
 
 
 
fac0133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d084ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fac0133
 
 
d084ead
 
 
 
 
 
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
'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useProcessingStatus } from '@/hooks/useStatementAPI';
import { apiClient } from '@/services/api-client';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FileText,
  Search,
  Zap,
  BarChart3,
  FileCheck,
  CheckCircle,
  AlertCircle,
  Loader2,
  Clock,
  CalendarDays,
  AlertTriangle,
} from 'lucide-react';

const STEP_ICONS = {
  read: FileText,
  detect: Search,
  extract: Zap,
  audit: BarChart3,
  generate: FileCheck,
};

const STEP_META = [
  { id: 'read', title: 'Reading PDF', description: 'Extracting document pages and content' },
  { id: 'detect', title: 'Detecting Bank', description: 'Identifying bank statement format' },
  { id: 'extract', title: 'Extracting Transactions', description: 'Parsing transaction records' },
  { id: 'audit', title: 'Running Audits', description: 'Validating and reconciling data' },
  { id: 'generate', title: 'Generating Workbook', description: 'Creating Excel workbook output' },
];

export function ProcessingFeature() {
  const params = useParams();
  const router = useRouter();
  const statementId = params.statementId as string;

  const { data: statusData, isError, isFetching } = useProcessingStatus(statementId, true);
  
  const [monthsWarning, setMonthsWarning] = useState<{ months: number; label: string } | null>(null);
  const [showMonthsModal, setShowMonthsModal] = useState(false);
  const [allowRedirect, setAllowRedirect] = useState(false);

  // When processing completes, fetch export summary to check months
  useEffect(() => {
    if (statusData?.overallProgress === 100 && !allowRedirect) {
      apiClient.getExportSummary(statementId)
        .then((summary) => {
          if (summary.monthsAvailable !== undefined && summary.monthsAvailable < 3) {
            setMonthsWarning({
              months: summary.monthsAvailable,
              label: summary.monthRangeLabel || '',
            });
            setShowMonthsModal(true);
          } else {
            setAllowRedirect(true);
          }
        })
        .catch((err) => {
          console.error('Failed to fetch export summary:', err);
          // If fetch fails, just allow redirect
          setAllowRedirect(true);
        });
    }
  }, [statusData?.overallProgress, statementId, allowRedirect]);

  // Redirect to review once allowed
  useEffect(() => {
    let timer: ReturnType<typeof setTimeout> | undefined;

    if (statusData?.overallProgress === 100 && allowRedirect) {
      timer = setTimeout(() => {
        router.push(`/review/${statementId}`);
      }, 1500);
    }

    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [statusData?.overallProgress, allowRedirect, isFetching, router, statementId]);

  const stages = statusData?.stages || STEP_META.map((s) => ({ key: s.id, label: s.title, status: 'pending' as const, progress: 0 }));
  const overallProgress = statusData?.overallProgress ?? 0;
  const estimatedSeconds = statusData?.estimatedSecondsRemaining;

  return (
    <div className="min-h-full bg-background flex flex-col items-center justify-center p-8">

      {/* Months warning modal — requires explicit OK to continue */}

      <AnimatePresence>

        {showMonthsModal && monthsWarning && (

          <div className="fixed inset-0 z-50 flex items-center justify-center">

            {/* Backdrop */}

            <motion.div

              className="absolute inset-0 bg-black/40"

              initial={{ opacity: 0 }}

              animate={{ opacity: 1 }}

              exit={{ opacity: 0 }}

              transition={{ duration: 0.2 }}

            />



            {/* Modal card */}

            <motion.div

              role="alertdialog"

              aria-modal="true"

              aria-labelledby="months-warning-title"

              aria-describedby="months-warning-desc"

              className="relative z-10 w-full max-w-sm mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden"

              initial={{ opacity: 0, scale: 0.92, y: 16 }}

              animate={{ opacity: 1, scale: 1, y: 0 }}

              exit={{ opacity: 0, scale: 0.92, y: 16 }}

              transition={{ type: 'spring', duration: 0.35, bounce: 0.2 }}

            >

              {/* Amber header strip */}

              <div className="bg-amber-50 border-b border-amber-100 px-5 pt-5 pb-4">

                <div className="flex items-center gap-2.5 mb-1">

                  <div className="w-8 h-8 rounded-full bg-amber-100 flex items-center justify-center flex-shrink-0">

                    <AlertTriangle className="w-4 h-4 text-amber-600" />

                  </div>

                  <h2

                    id="months-warning-title"

                    className="text-base font-bold text-amber-900"

                  >

                    Incomplete Statement Period

                  </h2>

                </div>

              </div>



              {/* Body */}

              <div id="months-warning-desc" className="px-5 py-4 space-y-3">

                {/* Months chip */}

                <div className="flex items-center justify-between rounded-lg bg-blue-50 border border-blue-100 px-4 py-3">

                  <div className="flex items-center gap-2 text-sm text-blue-700 font-medium">

                    <CalendarDays className="w-4 h-4" />

                    Months uploaded

                  </div>

                  <span className="text-lg font-bold text-blue-900">

                    {monthsWarning.months}

                  </span>

                </div>



                {monthsWarning.label && (

                  <div className="flex items-center justify-between rounded-lg bg-gray-50 border border-gray-100 px-4 py-2.5">

                    <span className="text-xs text-gray-500 font-medium">Period</span>

                    <span className="text-xs font-semibold text-gray-700">{monthsWarning.label}</span>

                  </div>

                )}



                <p className="text-sm text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2.5 leading-relaxed">

                  Only{' '}

                  <strong>

                    {monthsWarning.months} month{monthsWarning.months === 1 ? '' : 's'}

                  </strong>{' '}

                  of data was detected. Monthly averages in the export will still use a{' '}

                  <strong>3-month divisor</strong> — missing months are treated as{' '}

                  <strong>$0</strong>.

                </p>



                <p className="text-xs text-gray-500">

                  You can upload additional statements later to improve the accuracy of monthly averages.

                </p>

              </div>



              {/* Footer */}

              <div className="px-5 pb-5">

                <button

                  onClick={() => {

                    setShowMonthsModal(false);

                    setAllowRedirect(true);

                  }}

                  className="w-full rounded-xl bg-navy text-white text-sm font-semibold py-2.5 hover:opacity-90 active:scale-[0.98] transition-all"

                >

                  OK, I understand

                </button>

              </div>

            </motion.div>

          </div>

        )}

      </AnimatePresence>

      <motion.div

        initial={{ opacity: 0, y: 24 }}

        animate={{ opacity: 1, y: 0 }}

        transition={{ duration: 0.4 }}

        className="w-full max-w-2xl"

      >

        {/* Header */}

        <div className="text-center mb-10">

          <h1 className="text-2xl font-bold text-navy mb-2">Processing Statement</h1>

          <p className="text-gray-500 text-sm">

            Please wait while we extract and validate your bank statement

          </p>

        </div>



        {/* Overall Progress */}

        <div className="card p-6 mb-6">

          <div className="flex items-center justify-between mb-3">

            <span className="text-sm font-medium text-navy">Overall Progress</span>

            <span className="text-sm font-bold text-primary">{overallProgress}%</span>

          </div>

          <div className="h-2 bg-gray-100 rounded-full overflow-hidden">

            <motion.div

              className="h-full bg-primary rounded-full"

              initial={{ width: 0 }}

              animate={{ width: `${overallProgress}%` }}

              style={{ width: `${overallProgress}%` }}

              transition={{ duration: 0.4, ease: 'easeOut' }}

            />

          </div>

          {estimatedSeconds != null && estimatedSeconds > 0 && (

            <div className="flex items-center gap-1.5 mt-3 text-xs text-gray-500">

              <Clock className="w-3.5 h-3.5" />

              <span>~{estimatedSeconds}s remaining</span>

            </div>

          )}

        </div>



        {/* Pipeline Steps */}

        <div className="card divide-y divide-gray-100 overflow-hidden">

          {STEP_META.map((meta, idx) => {

            const stage = stages.find((s) => s.key === meta.id);

            const status = stage?.status ?? 'pending';

            const progress = stage?.progress ?? 0;

            const Icon = STEP_ICONS[meta.id as keyof typeof STEP_ICONS];



            return (

              <motion.div

                key={meta.id}

                initial={{ opacity: 0, x: -12 }}

                animate={{ opacity: 1, x: 0 }}

                transition={{ delay: idx * 0.07, duration: 0.3 }}

                className="flex items-start gap-4 p-5"

              >

                {/* Step Icon */}

                <div

                  className={[

                    'w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5',

                    status === 'completed' ? 'bg-success/10' :

                    status === 'active' ? 'bg-primary/10' :

                    status === 'failed' ? 'bg-error/10' :

                    'bg-gray-100',

                  ].join(' ')}

                >

                  {status === 'completed' ? (

                    <CheckCircle className="w-5 h-5 text-success" />

                  ) : status === 'failed' ? (

                    <AlertCircle className="w-5 h-5 text-error" />

                  ) : status === 'active' ? (

                    <Loader2 className="w-5 h-5 text-primary animate-spin" />

                  ) : (

                    <Icon className="w-5 h-5 text-gray-400" />

                  )}

                </div>



                {/* Step Info */}

                <div className="flex-1 min-w-0">

                  <div className="flex items-center justify-between mb-1">

                    <p

                      className={[

                        'text-sm font-semibold',

                        status === 'completed' ? 'text-success' :

                        status === 'active' ? 'text-primary' :

                        status === 'failed' ? 'text-error' :

                        'text-gray-400',

                      ].join(' ')}

                    >

                      {meta.title}

                    </p>

                    {status === 'active' && (

                      <span className="text-xs text-primary font-medium">{progress}%</span>

                    )}

                    {status === 'completed' && (

                      <span className="text-xs text-success font-medium">Done</span>

                    )}

                  </div>



                  <p className="text-xs text-gray-500 mb-2">{meta.description}</p>



                  {status === 'active' && (

                    <div className="h-1 bg-gray-100 rounded-full overflow-hidden">

                      <motion.div

                        className="h-full bg-primary rounded-full"

                        initial={{ width: 0 }}

                        animate={{ width: `${progress}%` }}

                        style={{ width: `${progress}%` }}

                        transition={{ duration: 0.4, ease: 'easeOut' }}

                      />

                    </div>

                  )}

                </div>

              </motion.div>

            );

          })}

        </div>



        {/* Error State */}

        {isError && (

          <motion.div

            initial={{ opacity: 0 }}

            animate={{ opacity: 1 }}

            className="mt-6 p-4 rounded-lg bg-error/10 border border-error/20 text-sm text-error text-center"

          >

            Processing failed. Please try again or contact support.

          </motion.div>

        )}



        {/* Completion */}

        {overallProgress === 100 && (

          <motion.div

            initial={{ opacity: 0, scale: 0.95 }}

            animate={{ opacity: 1, scale: 1 }}

            className="mt-6 p-4 rounded-lg bg-success/10 border border-success/20 text-sm text-success text-center font-medium"

          >

            {showMonthsModal

              ? '✓ Processing complete — please review the notice above to continue…'

              : '✓ Processing complete — redirecting to Review Workspace…'}

          </motion.div>

        )}

      </motion.div>

    </div>
  );
}