summaryrefslogtreecommitdiff
path: root/src/lib/transaction/components/Transaction.jsx
blob: 5ee569728035dbc011db000af46f7e8f5df474ae (plain)
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
import Spinner from '@/core/components/elements/Spinner/Spinner';
import NextImage from 'next/image';
import rejectImage from '../../../../public/images/reject.png';
import useTransaction from '../hooks/useTransaction';
import TransactionStatusBadge from './TransactionStatusBadge';
import Divider from '@/core/components/elements/Divider/Divider';
import { useEffect, useMemo, useRef, useState } from 'react';
import ImageNext from 'next/image';
import {
  downloadPurchaseOrder,
  downloadQuotation,
} from '../utils/transactions';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import uploadPoApi from '../api/uploadPoApi';
import { toast } from 'react-hot-toast';
import getFileBase64 from '@/core/utils/getFileBase64';
import currencyFormat from '@/core/utils/currencyFormat';
import VariantGroupCard from '@/lib/variant/components/VariantGroupCard';
import {
  EllipsisVerticalIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  ChevronUpIcon,
} from '@heroicons/react/24/outline';
import Link from '@/core/components/elements/Link/Link';
import checkoutPoApi from '../api/checkoutPoApi';
import cancelTransactionApi from '../api/cancelTransactionApi';
import MobileView from '@/core/components/views/MobileView';
import DesktopView from '@/core/components/views/DesktopView';
import Menu from '@/lib/auth/components/Menu';
import Image from '@/core/components/elements/Image/Image';
import { createSlug } from '@/core/utils/slug';
import toTitleCase from '@/core/utils/toTitleCase';
import useAirwayBill from '../hooks/useAirwayBill';
import Manifest from '@/lib/treckingAwb/component/Manifest';
import useAuth from '@/core/hooks/useAuth';
import StepApproval from './stepper';
import aprpoveApi from '../api/approveApi';
import rejectApi from '../api/rejectApi';
import rejectProductApi from '../api/rejectProductApi';
import { useRouter } from 'next/router';
import { gtagPurchase } from '@/core/utils/googleTag';
import { deleteItemCart } from '@/core/utils/cart';
import {
  downloadInvoice,
  // downloadTaxInvoice, // (unused)
} from '@/lib/invoice/utils/invoices';
import { Download } from 'lucide-react';
import axios from 'axios';
import InformationSection from '../../treckingAwb/component/InformationSection';
// import { Button } from '@chakra-ui/react'; // (unused)
// import { div } from 'lodash-contrib'; // (unused)

const Transaction = ({ id }) => {
  const PPN = process.env.NEXT_PUBLIC_PPN;
  const router = useRouter();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [reason, setReason] = useState('');
  const auth = useAuth();
  const { transaction } = useTransaction({ id });
  const statusApprovalWeb = transaction.data?.approvalStep;
  const [isLoading, setIsLoading] = useState(false);
  const { queryAirwayBill } = useAirwayBill({ orderId: id });
  const [airwayBillPopup, setAirwayBillPopup] = useState(null);
  const [isOpen, setIsOpen] = useState(false);
  const poNumber = useRef(null);
  const poFile = useRef(null);
  const [uploadPo, setUploadPo] = useState(false);
  const [idAWB, setIdAWB] = useState(null);
  const openUploadPo = () => setUploadPo(true);
  const closeUploadPo = () => setUploadPo(false);
  const [copied, setCopied] = useState(false);
  const [toOthers, setToOthers] = useState(null);
  const [totalAmount, setTotalAmount] = useState(0);
  const [totalDiscountAmount, setTotalDiscountAmount] = useState(0);
  const [contLoading, setContLoading] = useState(false);

  useEffect(() => {
    if (transaction?.data?.products) {
      let calculateTotalAmount = 0;
      let calculateTotalDiscountAmount = 0;
      transaction.data.products.forEach((product) => {
        calculateTotalAmount += product.price.price * product.quantity;
        calculateTotalDiscountAmount +=
          (product.price.price - product.price.priceDiscount) *
          product.quantity;
      });
      setTotalAmount(calculateTotalAmount);
      setTotalDiscountAmount(calculateTotalDiscountAmount);
    }
  }, [transaction.data, transaction.isLoading]);

  const submitUploadPo = async () => {
    const file = poFile.current.files[0];
    const name = poNumber.current.value;
    if (typeof file === 'undefined' || !name) {
      toast.error('Nomor dan Dokumen PO harus diisi');
      return;
    }
    if (file.size > 5000000) {
      toast.error('Maksimal ukuran file adalah 5MB');
      return;
    }
    const data = { name, file: await getFileBase64(file) };
    const isUploaded = await uploadPoApi({ id, data });
    if (isUploaded) {
      toast.success('Berhasil upload PO');
      transaction.refetch();
      closeUploadPo();
      return;
    }
    toast.error(
      'Terjadi kesalahan internal, coba lagi nanti atau hubungi kami'
    );
  };

  const [cancelTransaction, setCancelTransaction] = useState(false);
  const [continueNoPo, setContinueNoPo] = useState(false);
  const [continueTransaction, setContinueTransaction] = useState(false);
  const openCancelTransaction = () => setCancelTransaction(true);
  const openContinueTransaction = () => {
    if (auth.partnerTempo) {
      checkout();
    } else {
      if (!transaction.data?.purchaseOrderFile) {
        setContinueTransaction(true);
      } else {
        checkoutNoPO();
      }
    }
  };
  const closeCancelTransaction = () => setCancelTransaction(false);
  const closeContinueTransaction = () => setContinueTransaction(false);

  const [rejectTransaction, setRejectTransaction] = useState(false);

  const openRejectTransaction = () => setRejectTransaction(true);
  const closeRejectTransaction = () => setRejectTransaction(false);

  const submitCancelTransaction = async () => {
    const isCancelled = await cancelTransactionApi({
      transaction: transaction.data,
    });
    if (isCancelled) {
      toast.success('Berhasil batalkan transaksi');
      transaction.refetch();
    }
    closeCancelTransaction();
  };

  const checkout = async () => {
    if (!transaction.data?.purchaseOrderFile) {
      toast.error('Mohon upload dokumen PO anda sebelum melanjutkan pesanan');
      return;
    }
    await checkoutPoApi({ id, status: true });
    toast.success('Berhasil melanjutkan pesanan');
    transaction.refetch();
  };

  const checkoutNoPO = async () => {
    setIsLoading(true);
    gtagPurchase(
      transaction.data.products,
      transaction.data.deliveryAmount,
      transaction.data.name
    );

    gtag('event', 'conversion', {
      send_to: 'AW-954540379/nDymCL3BhaQYENvClMcD',
      value:
        transaction.data?.amountTotal +
        Math.round(parseInt(transaction.data.deliveryAmount * 1.1) / 1000) *
          1000,
      currency: 'IDR',
      transaction_id: transaction.data.id,
    });

    for (const product of transaction.data.products)
      deleteItemCart({ productId: product.id });
    if (transaction.data?.amountTotal > 0) {
      const payment = await axios.post(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/midtrans-payment?transactionId=${transaction.data.id}`
      );
      setIsLoading(false);
      window.location.href = payment.data.redirectUrl;
    } else {
      window.location.href = `${
        process.env.NEXT_PUBLIC_SELF_HOST
      }/shop/checkout/success?order_id=${transaction.data.name.replace(
        /\//g,
        '-'
      )}`;
    }
    toast.success('Berhasil melanjutkan pesanan');
    transaction.refetch();
  };

  const handleApproval = async () => {
    await aprpoveApi({ id });
    toast.success('Berhasil melanjutkan approval');
    transaction.refetch();
  };

  const handleReject = async () => {
    await rejectApi({ id });
    closeRejectTransaction();
    transaction.refetch();
  };

  // ===== Bayar Sekarang (pakai link dari backend; fallback generate via Next API) =====
  const handlePayNow = async () => {
    try {
      setContLoading(true);

      const base = (process.env.NEXT_PUBLIC_ODOO_API_HOST || '').replace(
        /\/$/,
        ''
      );
      const token = auth?.token;
      const partnerId = auth?.partnerId;

      // 1) Minta Odoo ensure payment link
      const { data: resp } = await axios.get(
        `${base}/api/v1/partner/${partnerId}/sale_order/${transaction.data.id}`,
        {
          params: { ensure_payment_link: 1, ts: Date.now() },
          headers: { Token: token },
        }
      );

      // console.log('API Response:', resp); // Debug

      // 2) Akses semua kemungkinan path
      let url =
        resp?.result?.payment_summary?.redirect_url ||
        resp?.data?.result?.payment_summary?.redirect_url ||
        resp?.payment_summary?.redirect_url ||
        resp?.paymentSummary?.redirectUrl ||
        '';

      // console.log('Extracted URL:', url); // Debug

      if (url) {
        window.location.href = url;
        return;
      }

      // 3) Fallback
      await transaction.refetch();
      // console.log('Transaction data:', transaction.data); // Debug

      url =
        transaction?.data?.result?.payment_summary?.redirect_url ||
        transaction?.data?.paymentSummary?.redirectUrl ||
        transaction?.data?.payment_summary?.redirect_url ||
        '';

      // console.log('Fallback URL:', url); // Debug

      if (url) {
        window.location.href = url;
        return;
      }

      throw new Error('Link pembayaran belum tersedia.');
    } catch (e) {
      toast.error(
        e?.response?.data?.description ||
          e?.message ||
          'Gagal membuka pembayaran'
      );
    } finally {
      setContLoading(false);
    }
  };

  const memoizeVariantGroupCard = useMemo(
    () => (
      <div className='p-4 pt-0 flex flex-col gap-y-3'>
        <VariantGroupCard variants={transaction.data?.products} buyMore />
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>Subtotal</p>
          <p>{currencyFormat(transaction.data?.amountUntaxed)}</p>
        </div>
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>
            PPN {((PPN - 1) * 100).toFixed(0)}%
          </p>
          <p>{currencyFormat(transaction.data?.amountTax)}</p>
        </div>
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>Biaya Pengiriman</p>
          <p>{currencyFormat(transaction.data?.deliveryAmount)}</p>
        </div>
        <div className='flex justify-between mt-1 font-medium'>
          <p>Grand Total</p>
          <p>{currencyFormat(transaction.data?.amountTotal)}</p>
        </div>
      </div>
    ),
    [transaction.data]
  );

  const memoizeVariantGroupCardReject = useMemo(
    () => (
      <div className='p-4 pt-0 flex flex-col gap-y-3'>
        <VariantGroupCard
          variants={transaction.data?.productsRejectLine}
          buyMore
        />
      </div>
    ),
    [transaction.data]
  );

  if (transaction.isLoading) {
    return (
      <div className='flex justify-center my-6'>
        <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
      </div>
    );
  }

  const closePopup = () => {
    setIdAWB(null);
  };

  const openModal = (product) => {
    setSelectedProduct(product);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setSelectedProduct(null);
    setReason('');
  };

  const handleRejectProduct = async () => {
    try {
      if (!reason.trim()) {
        toast.error('Masukkan alasan terlebih dahulu');
        return;
      } else {
        let idSo = transaction?.data.id;
        let idProduct = selectedProduct?.id;
        await rejectProductApi({ idSo, idProduct, reason });
        closeModal();
        toast.success('Produk berhasil di reject');
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      }
    } catch (error) {
      toast.error('Gagal reject produk. Silakan coba lagi.');
    }
  };

  const handleCopyClick = (waybillNumber) => {
    const textToCopy = waybillNumber;
    navigator.clipboard.writeText(textToCopy);
    setCopied(true);
    toast.success('No Resi Berhasil di Copy');
    setTimeout(() => setCopied(false), 2000);
  };

  const formatDate = (dateString) => {
    const months = [
      'Januari',
      'Februari',
      'Maret',
      'April',
      'Mei',
      'Juni',
      'Juli',
      'Agustus',
      'September',
      'Oktober',
      'November',
      'Desember',
    ];

    const [day, month, year] = dateString.split('/');
    return `${day} ${months[parseInt(month, 10) - 1]} ${year}`;
  };

  return (
    transaction.data?.name && (
      <>
        <BottomPopup
          active={continueTransaction}
          close={closeContinueTransaction}
          title='Lanjutkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin melanjutkan tanpa upload PO?{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={checkoutNoPO}
            >
              Ya, Lanjutkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeContinueTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>

        <BottomPopup
          active={cancelTransaction}
          close={closeCancelTransaction}
          title='Batalkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin membatalkan transaksi{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={submitCancelTransaction}
            >
              Ya, Batalkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeCancelTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>

        <BottomPopup
          active={rejectTransaction}
          close={closeRejectTransaction}
          title='Batalkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin Membatalkan transaksi{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={handleReject}
            >
              Ya, Batalkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeRejectTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>

        <BottomPopup title='Upload PO' close={closeUploadPo} active={uploadPo}>
          <div>
            <label>Nomor PO</label>
            <input type='text' className='form-input mt-3' ref={poNumber} />
          </div>
          <div className='mt-4'>
            <label>Dokumen PO</label>
            <input type='file' className='form-input mt-3 py-2' ref={poFile} />
          </div>
          <div className='grid grid-cols-2 gap-x-3 mt-6'>
            <button
              type='button'
              className='btn-light w-full'
              onClick={closeUploadPo}
            >
              Batal
            </button>
            <button
              type='button'
              className='btn-solid-red w-full'
              onClick={submitUploadPo}
            >
              Upload
            </button>
          </div>
        </BottomPopup>

        <BottomPopup
          title='Lainnya'
          active={toOthers}
          close={() => setToOthers(null)}
        >
          <div className='flex flex-col gap-y-4 mt-2'>
            <button
              className='text-left disabled:opacity-60'
              disabled={!toOthers?.purchaseOrderFile}
              onClick={() => {
                downloadPurchaseOrder(toOthers);
                setToOthers(null);
              }}
            >
              Download PO
            </button>
            <button
              className='text-left disabled:opacity-60'
              disabled={toOthers?.status != 'draft'}
              onClick={() => {
                downloadQuotation(toOthers);
                setToOthers(null);
              }}
            >
              Download Quotation
            </button>
            <button
              className='text-left disabled:opacity-60'
              disabled={toOthers?.status != 'waiting'}
              onClick={() => {
                setToCancel(toOthers);
                setToOthers(null);
              }}
            >
              Batalkan Transaksi
            </button>
          </div>
        </BottomPopup>

        <Manifest idAWB={idAWB} closePopup={closePopup}></Manifest>

        {/* ============ MOBILE ============ */}
        <MobileView>
          <div className='px-4'>
            <div className='flex flex-row w-full justify-between items-center py-2 px-3 mb-4 text-sm border border-yellow-500 text-yellow-800 rounded-lg bg-yellow-50 gap-2'>
              <div className='flex items-center w-full ' role='alert'>
                <svg
                  className='flex-shrink-0 inline w-4 h-4 mr-2'
                  aria-hidden='true'
                  fill='currentColor'
                  viewBox='0 0 20 20'
                >
                  <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' />
                </svg>
                <div className='text-justify flex flex-col gap-1'>
                  <span className='text-black text-xs text-start'>
                    Pesanan anda mungkin mengalami keterlambatan tiba
                  </span>
                </div>
              </div>
              <span
                className='text-red-500 text-xs hover:cursor-pointer text-nowrap z-50'
                onClick={() => setIdAWB(transaction?.data?.pickings[0]?.id)}
              >
                Lihat Detail
              </span>
            </div>
          </div>

          {auth?.feature?.soApproval && (
            <div className='p-4'>
              <StepApproval
                layer={statusApprovalWeb}
                status={transaction?.data?.status}
                className='ml-auto'
              />
            </div>
          )}

          <div className='flex flex-row justify-between items-center gap-2 px-4'>
            <div className='flex flex-col justify-start items-start gap-2'>
              <div className='font-semibold'>{transaction.data?.name}</div>
              <TransactionStatusBadge status={transaction.data?.status} />
            </div>
            <div>
              <EllipsisVerticalIcon
                className='w-5 h-5'
                onClick={() => setToOthers(transaction?.data)}
              />
            </div>
          </div>

          {transaction.data?.invoices?.length === 0 ? (
            <h1 className=''></h1>
          ) : (
            transaction.data?.invoices?.map((invoice, index) => (
              <div
                className='flex flex-row justify-between items-center gap-2 p-4'
                key={index}
              >
                <div className=''>{invoice?.name}</div>
                <span
                  className='text-red-500'
                  onClick={() => downloadInvoice(invoice)}
                >
                  Download
                </span>
              </div>
            ))
          )}

          <Divider />

          <div className='flex flex-col gap-y-4 p-4'>
            <h4 className='font-semibold'>Detail Order</h4>
            <DescriptionRow label='No Transaksi'>
              <p className='font-semibold'>{transaction.data?.name}</p>
            </DescriptionRow>
            <DescriptionRow label='Tanggal Transaksi'>
              {transaction.data?.dateOrder
                ? formatDate(transaction.data?.dateOrder)
                : '-'}
            </DescriptionRow>
            <DescriptionRow label='Purchase Order'>
              {transaction.data?.purchaseOrderName || '-'}
            </DescriptionRow>
            <DescriptionRow label='Nama Sales'>
              {transaction.data?.sales}
            </DescriptionRow>
          </div>

          <Divider />

          <div className='flex flex-col gap-y-4 p-4'>
            <h4 className='font-semibold'>Alamat Pengiriman</h4>
            <DescriptionRow label='Nama Penerima'>
              <p className='font-semibold'>
                {transaction?.data?.address?.customer?.name}
              </p>
            </DescriptionRow>
            <DescriptionRow label='No. Telp'>
              {transaction?.data?.address?.customer?.phone
                ? transaction?.data?.address?.customer?.phone
                : '-'}
            </DescriptionRow>
            <DescriptionRow label='Email'>
              {transaction?.data?.address?.customer?.email
                ? transaction?.data?.address?.customer?.email
                : '-'}
            </DescriptionRow>
            <DescriptionRow label='Alamat Pengiriman'>
              {transaction?.data?.address?.customer?.alamatBisnis}
            </DescriptionRow>
          </div>

          <Divider />
          <div className='p-4'>
            <div className='font-medium mb-4'>Info Pengiriman</div>
            {transaction?.data?.pickings.length == 0 && (
              <div className='badge-red text-sm'>Belum ada pengiriman</div>
            )}
            {transaction?.data?.pickings?.map((airway) => (
              <div
                key={airway?.id}
                className='border border-gray_r-6 rounded mb-3'
              >
                <InformationSection manifests={airway} />
                <div className='p-4'>
                  <button
                    className='bg-transparent text-red-600 hover:underline p-0 font-semibold'
                    onClick={() => {
                      if (airway?.waybillNumber == '-') {
                        toast.error('Nomor Resi belum tersedia');
                        return;
                      }
                      setIdAWB(airway.id);
                    }}
                  >
                    Lacak Pengiriman
                  </button>
                </div>
              </div>
            ))}
          </div>

          <Divider />

          <div className='p-4'>
            <p className='font-medium'>Invoice</p>
            <div className='flex flex-col gap-y-3 mt-4'>
              {transaction.data?.invoices?.map((invoice, index) => (
                <Link href={`/my/invoices/${invoice.id}`} key={index}>
                  <div className='shadow rounded-md p-4 text-gray_r-12 font-normal flex justify-between'>
                    <div>
                      <p className='mb-2'>{invoice?.name}</p>
                      <div className='flex items-center gap-x-1'>
                        {invoice.amountResidual > 0 ? (
                          <div className='badge-red'>Belum Lunas</div>
                        ) : (
                          <div className='badge-green'>Lunas</div>
                        )}
                        <p className='text-caption-2 text-gray_r-11'>
                          {currencyFormat(invoice.amountTotal)}
                        </p>
                      </div>
                    </div>
                    <ChevronRightIcon className='w-5 stroke-2' />
                  </div>
                </Link>
              ))}
              {transaction.data?.invoices?.length === 0 && (
                <div className='badge-red text-sm px-2'>Belum ada invoice</div>
              )}
            </div>
          </div>

          <Divider />

          {!auth?.feature.soApproval && (
            <div className='p-4 flex flex-col gap-y-4'>
              <DescriptionRow label='Purchase Order'>
                {transaction.data?.purchaseOrderName || '-'}
              </DescriptionRow>
              <div className='flex items-center justify-between'>
                <p className='text-gray_r-11 leading-none'>Dokumen PO : </p>
                <button
                  type='button'
                  className='inline-block text-danger-500'
                  onClick={
                    transaction.data?.purchaseOrderFile
                      ? () => downloadPurchaseOrder(transaction.data)
                      : transaction?.data.invoices.length < 1
                      ? openUploadPo
                      : ''
                  }
                >
                  {transaction?.data?.purchaseOrderFile
                    ? 'Download'
                    : transaction?.data.invoices.length < 1
                    ? 'Upload'
                    : '-'}
                </button>
              </div>
            </div>
          )}

          <Divider />

          <div className='font-medium p-4'>Detail Produk</div>
          {transaction?.data?.products.length > 0 ? (
            <div className='p-4 pt-0 flex flex-col gap-y-3'>
              <VariantGroupCard variants={transaction.data?.products} />
              <div className='font-medium'>Rincian Pembayaran</div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Metode Pembayaran</p>
                <p>{transaction.data?.paymentTerm || '-'}</p>
              </div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Berat Barang</p>
                <p>
                  {transaction.data?.products?.reduce(
                    (total, item) => total + (item.weight || 0),
                    0
                  ) + ' Kg'}
                </p>
              </div>
              <hr className='mt-1 border border-gray-100' />
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Total Belanja</p>
                <p>{currencyFormat(totalAmount)}</p>
              </div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Diskon Belanja</p>
                <p>{'- ' + currencyFormat(totalDiscountAmount)}</p>
              </div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Subtotal</p>
                <p>{currencyFormat(transaction.data?.amountUntaxed)}</p>
              </div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>
                  PPN {((PPN - 1) * 100).toFixed(0)}%
                </p>
                <p>{currencyFormat(transaction.data?.amountTax)}</p>
              </div>
              <div className='flex justify-between mt-1'>
                <p className='text-gray_r-12/70'>Biaya Pengiriman</p>
                <p>{currencyFormat(transaction.data?.deliveryAmount)}</p>
              </div>
              <div className='flex justify-between mt-1 font-medium'>
                <p className='text-gray_r-12/70'>Asuransi Pengiriman</p>
                <p>-</p>
              </div>
              <div className='flex justify-between mt-1 font-medium'>
                <p>Grand Total</p>
                <p>{currencyFormat(transaction.data?.amountTotal)}</p>
              </div>
            </div>
          ) : (
            <div className='badge-red text-sm px-2 ml-4'>
              Semua produk telah di reject
            </div>
          )}

          {transaction?.data?.productsRejectLine.length > 0 && (
            <div>
              <div className='font-medium p-4'>Detail Produk Reject</div>
              {memoizeVariantGroupCardReject}
            </div>
          )}

          {/* Tombol aksi (Mobile) */}
          {transaction.data?.status === 'draft' && (
            <div className='p-4 pt-0'>
              <button
                className='btn-light w-full mt-4'
                disabled={transaction.data?.status != 'draft'}
                onClick={() => downloadQuotation(transaction.data)}
              >
                Download Quotation
              </button>
              <button
                className='btn-solid-red w-full mt-4'
                onClick={openCancelTransaction}
              >
                Batalkan Transaksi
              </button>
              {transaction.data?.status == 'draft' &&
                transaction?.data?.purchaseOrderFile && (
                  <button
                    className='btn-yellow w-full mt-4'
                    onClick={openContinueTransaction}
                  >
                    Lanjutkan Transaksi
                  </button>
                )}
            </div>
          )}

          {/* Bayar Sekarang (Mobile) — tampil jika eligible */}
          {transaction.data?.eligibleContinue && (
            <div className='p-4 pt-0'>
              <button
                type='button'
                disabled={contLoading}
                onClick={handlePayNow}
                className='w-full py-2 text-center rounded-md border border-red-500 text-red-500 bg-white disabled:opacity-60'
              >
                {contLoading ? 'Memproses…' : 'Bayar Sekarang'}
              </button>
            </div>
          )}
        </MobileView>

        {/* ============ DESKTOP ============ */}
        <DesktopView>
          <div className='container mx-auto flex py-10'>
            <div className='w-3/12 pr-4'>
              <Menu />
            </div>
            <div className='w-9/12 p-4 py-6 bg-white border border-gray_r-6 rounded'>
              <div className='flex justify-between'>
                <h1 className='text-title-sm font-semibold mb-6'>
                  Detail Transaksi
                </h1>
                {auth?.feature?.soApproval && (
                  <StepApproval
                    layer={statusApprovalWeb}
                    status={transaction?.data?.status}
                    className='ml-auto'
                  />
                )}
              </div>

              {/* HEADER (Desktop) — sejajarkan kiri & kanan */}
              <div className='flex items-center justify-between gap-3 mb-3'>
                {/* Kiri: SO + badge */}
                <div className='flex items-center gap-x-2 min-w-0'>
                  <span className='text-h-sm font-medium truncate'>
                    {transaction?.data?.name}
                  </span>
                  <TransactionStatusBadge status={transaction?.data?.status} />
                </div>

                {/* Kanan: aksi */}
                <div className='flex items-center gap-3'>
                  {transaction.data?.status === 'draft' && (
                    <>
                      <button
                        type='button'
                        className='btn-light px-3 py-2'
                        onClick={() => downloadQuotation(transaction.data)}
                      >
                        <Download size={12} />
                      </button>

                      <button
                        className='btn-solid-red'
                        onClick={openCancelTransaction}
                      >
                        Batalkan Transaksi
                      </button>

                      {transaction?.data?.purchaseOrderFile && (
                        <button
                          className='btn-yellow'
                          onClick={openContinueTransaction}
                        >
                          Lanjutkan Transaksi
                        </button>
                      )}
                    </>
                  )}

                  {transaction.data?.eligibleContinue && (
                    <button
                      className='px-4 py-2 rounded-md border border-red-500 text-red-500 bg-white disabled:opacity-60 mb-3'
                      disabled={contLoading}
                      onClick={handlePayNow}
                    >
                      {contLoading ? 'Memproses…' : 'Bayar Sekarang'}
                    </button>
                  )}
                </div>
              </div>

              <div className='grid grid-cols-2 gap-x-6 mt-4'>
                <div className='grid grid-cols-[35%_65%] gap-y-4'>
                  <div>Nama Sales</div>
                  <div>: {transaction?.data?.sales}</div>

                  <div>Tanggal Transaksi</div>
                  <div>: {transaction?.data?.dateOrder}</div>

                  {!auth?.feature?.soApproval ? (
                    <>
                      <div>Purchase Order</div>
                      <div>
                        : {transaction?.data?.purchaseOrderName}{' '}
                        <button
                          type='button'
                          className='inline-block text-danger-500'
                          onClick={
                            transaction.data?.purchaseOrderFile
                              ? () => downloadPurchaseOrder(transaction.data)
                              : transaction?.data.invoices.length < 1
                              ? openUploadPo
                              : ''
                          }
                        >
                          {transaction?.data?.purchaseOrderFile
                            ? 'Download'
                            : transaction?.data.invoices.length < 1
                            ? 'Upload'
                            : '-'}
                        </button>
                      </div>
                    </>
                  ) : (
                    <>
                      <div>Site</div>
                      <div>: {transaction?.data?.sitePartner}</div>
                    </>
                  )}
                </div>
                <div className='grid grid-cols-[35%_65%] gap-y-4'>
                  <div>Payment Term</div>
                  <div>: {transaction?.data?.paymentTerm}</div>

                  <div>Dokumen Pengiriman</div>
                  <div>
                    :{' '}
                    {transaction.data?.pickings?.length === 0
                      ? 'Belum ada pengiriman'
                      : transaction?.data?.pickings[0].name}
                  </div>

                  <div>Invoice Pembelian</div>
                  <div>
                    :{' '}
                    {transaction.data?.invoices?.length === 0
                      ? 'Belum ada invoice'
                      : transaction.data?.invoices?.map((invoice, index) => (
                          <Link
                            href={`/my/invoices/${invoice.id}`}
                            className='contents'
                            key={index}
                          >
                            {invoice?.name}
                          </Link>
                        ))}
                  </div>
                </div>
              </div>
              <hr className='mt-4 mb-4 border border-gray-100' />

              <div className='flex flex-row justify-between items-start w-full h-fit '>
                <div className='flex flex-col w-1/2 justify-start items-start'>
                  <span className='text-h-sm font-medium mb-2'>
                    Alamat Pengiriman
                  </span>
                  <div className='grid grid-cols-[34%_2%_64%] gap-y-4'>
                    <div>Nama Penerima</div>
                    <div>: </div>
                    <div>{transaction?.data?.address?.customer?.name}</div>

                    <div>No. Telepon</div>
                    <div>: </div>
                    <div>
                      {transaction?.data?.address?.customer?.phone
                        ? transaction?.data?.address?.customer?.phone
                        : '-'}
                    </div>

                    <div>Email</div>
                    <div>: </div>
                    <div>
                      {transaction?.data?.address?.customer?.email
                        ? transaction?.data?.address?.customer?.email
                        : '-'}
                    </div>

                    <div>Alamat Pengiriman</div>
                    <div>: </div>
                    <div className='text-indent-[2px]'>
                      {transaction?.data?.address?.customer?.alamatBisnis}
                    </div>
                  </div>
                </div>
                <div className='flex flex-col w-1/2 justify-start items-start'>
                  <span className='text-h-sm font-medium mb-2'>
                    Info Ekspedisi
                  </span>
                  <div className='grid grid-cols-[34%_2%_64%] gap-y-4  w-full'>
                    <div>Kurir</div>
                    <div>: </div>
                    {transaction?.data?.carrierName ? (
                      <div className='flex flex-row  w-full gap-1 items-center justify-start '>
                        <p className=' text-nowrap'>
                          {transaction?.data?.carrierName}
                        </p>
                      </div>
                    ) : (
                      '-'
                    )}
                    {transaction?.data?.carrierId !== 32 && (
                      <>
                        <div>Jenis Service</div>
                        <div>: </div>
                        <div>
                          {' '}
                          {transaction?.data?.serviceType
                            ? transaction?.data?.serviceType
                            : '-'}
                        </div>
                      </>
                    )}

                    <div>Estimasi Tanggal Kirim</div>
                    <div>: </div>
                    <div>
                      {transaction?.data?.expectedReadyToShip
                        ? transaction?.data?.expectedReadyToShip
                        : '-'}
                    </div>
                    {transaction?.data?.carrierId !== 32 && (
                      <>
                        <div>Estimasi Tiba</div>
                        <div>: </div>
                        <div className=''>
                          {transaction?.data?.etaDateStart &&
                          transaction?.data?.etaDateEnd
                            ? `${transaction.data.etaDateStart} - ${transaction.data.etaDateEnd}`
                            : '-'}
                        </div>
                      </>
                    )}
                    {transaction?.data?.pickings[0] &&
                      transaction?.data?.carrierId !== 32 && (
                        <div className='w-full bagian-informasi col-span-3'>
                          <div
                            className='flex items-center w-fit py-2 px-3 mb-4 text-sm border border-yellow-500 text-yellow-800 rounded-lg bg-yellow-50'
                            role='alert'
                          >
                            <svg
                              className='flex-shrink-0 inline w-4 h-4 mr-2'
                              aria-hidden='true'
                              fill='currentColor'
                              viewBox='0 0 20 20'
                            >
                              <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' />
                            </svg>
                            <div className='text-justify flex flex-col gap-1'>
                              <span className='text-black text-xs'>
                                Pesanan anda mungkin mengalami keterlambatan
                                tiba
                              </span>
                            </div>
                          </div>
                        </div>
                      )}
                  </div>
                </div>
              </div>

              <div className='text-h-sm font-semibold mt-4 mb-4'>
                Informasi Pengiriman
              </div>
              <div className='grid grid-cols-1 md:grid-cols-2 gap-3'>
                {transaction?.data?.pickings.length == 0 && (
                  <div className='badge-red text-sm'>Belum ada pengiriman</div>
                )}
                {transaction?.data?.pickings?.map((airway) => (
                  <div
                    key={airway?.id}
                    className='border border-gray_r-6 rounded p-3'
                  >
                    <InformationSection manifests={airway} />
                    <div className='p-4'>
                      <button
                        className='bg-transparent text-red-600 hover:underline p-0 font-semibold'
                        onClick={() => {
                          if (airway?.waybillNumber == '-') {
                            toast.error('Nomor Resi belum tersedia');
                            return;
                          }
                          setIdAWB(airway.id);
                        }}
                      >
                        Lacak Pengiriman
                      </button>
                    </div>
                  </div>
                ))}
              </div>

              <div className='flex '>
                <div className='invoice w-1/2 '>
                  <div className='text-h-sm font-semibold mt-10 mb-4 '>
                    Invoice
                  </div>
                  {transaction.data?.invoices?.length === 0 && (
                    <div className='badge-red text-sm'>Belum ada invoice</div>
                  )}
                  <div className='grid grid-cols-1 gap-1 w-2/3 '>
                    {transaction.data?.invoices?.map((invoice, index) => (
                      <Link href={`/my/invoices/${invoice.id}`} key={index}>
                        <div className='shadow rounded-md p-4 text-gray_r-12 font-normal flex justify-between'>
                          <div>
                            <p className='mb-1'>{invoice?.name}</p>
                            <div className='flex items-center gap-x-1'>
                              {invoice.amountResidual > 0 ? (
                                <div className='badge-red'>Belum Lunas</div>
                              ) : (
                                <div className='badge-green'>Lunas</div>
                              )}
                              <p className='text-caption-2 text-gray_r-11'>
                                {currencyFormat(invoice.amountTotal)}
                              </p>
                            </div>
                          </div>
                          <ChevronRightIcon className='w-5 stroke-2' />
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              </div>

              <div className='text-h-sm font-semibold mt-4 mb-4'>
                Rincian Pembelian
              </div>
              {transaction?.data?.products?.length > 0 ? (
                <table className='table-data'>
                  <thead>
                    <tr>
                      <th>Nama Produk</th>
                      <th>Jumlah</th>
                      <th>Harga</th>
                      <th>Subtotal</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {transaction?.data?.products?.map((product) => (
                      <tr key={product.id}>
                        <td className='flex'>
                          <Link
                            href={createSlug(
                              '/shop/product/',
                              product?.parent.name,
                              product?.parent.id
                            )}
                            className='w-[20%] flex-shrink-0'
                          >
                            <div className='relative'>
                              <Image
                                src={product?.parent?.image}
                                alt={product?.name}
                                className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                              />
                              <div className='absolute top-0 right-4 flex  mt-3'>
                                <div className='gambarB '>
                                  {product.isSni && (
                                    <ImageNext
                                      src='/images/sni-logo.png'
                                      alt='SNI Logo'
                                      className='w-2 h-4 object-contain object-top   sm:h-4'
                                      width={50}
                                      height={50}
                                    />
                                  )}
                                </div>
                                <div className='gambarC  '>
                                  {product.isTkdn && (
                                    <ImageNext
                                      src='/images/TKDN.png'
                                      alt='TKDN'
                                      className='w-5 h-4 object-contain object-top  ml-1 sm:h-4'
                                      width={50}
                                      height={50}
                                    />
                                  )}
                                </div>
                              </div>
                            </div>
                          </Link>
                          <div className='px-2 text-left'>
                            <Link
                              href={createSlug(
                                '/shop/product/',
                                product?.parent.name,
                                product?.parent.id
                              )}
                              className='line-clamp-2 leading-6 !text-gray_r-12 font-normal'
                            >
                              {product?.parent?.name}
                            </Link>
                            <div className='text-gray_r-11 mt-2'>
                              {product?.code}{' '}
                              {product?.attributes.length > 0
                                ? `| ${product?.attributes.join(', ')}`
                                : ''}
                            </div>
                            {product.soQty && (
                              <div className='text-[10px] text-red-500 italic mt-2'>
                                {product.soQty !== product.reservedStockQty
                                  ? 'Barang sedang disiapkan'
                                  : `${product.reservedStockQty} barang bisa di
                              kirim/pickup`}
                              </div>
                            )}
                          </div>
                        </td>
                        <td>{product.quantity}</td>
                        <td>
                          <div>
                            {currencyFormat(product.price.priceDiscount)}
                          </div>
                        </td>
                        <td>{currencyFormat(product.price.subtotal)}</td>
                        {auth?.feature.soApproval &&
                          (auth.webRole == 2 || auth.webRole == 3) &&
                          router.asPath.includes('/my/quotations/') &&
                          transaction.data?.status == 'draft' && (
                            <td>
                              <button
                                className='bg-red-500 text-white py-1 px-3 rounded'
                                onClick={() => openModal(product)}
                              >
                                Reject
                              </button>
                            </td>
                          )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div className='badge-red text-sm'>
                  Semua produk telah di reject
                </div>
              )}

              {isModalOpen && (
                <div className='fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center'>
                  <div
                    className='bg-white p-4 rounded w-96
                     ease-in-out opacity-100
                    transform transition-transform duration-300  scale-100'
                  >
                    <h2 className='text-lg mb-2'>Berikan Alasan</h2>
                    <textarea
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      className='w-full p-2 border rounded'
                      rows='4'
                    ></textarea>
                    <div className='mt-4 flex justify-end'>
                      <button
                        className='bg-gray-300 text-black py-1 px-3 rounded mr-2'
                        onClick={closeModal}
                      >
                        Batal
                      </button>
                      <button
                        className='bg-red-500 text-white py-1 px-3 rounded'
                        onClick={handleRejectProduct}
                      >
                        Reject
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {transaction?.data?.products?.length > 0 && (
                <div className='flex justify-end mt-4 flex-col items-end'>
                  <div className='w-1/4 grid grid-cols-2 gap-y-3 text-gray_r-12/80'>
                    <div className='text-right'>Total Belanja</div>
                    <div className='text-right font-medium'>
                      {currencyFormat(totalAmount)}
                    </div>

                    <div className='text-right'>Total Diskon</div>
                    <div className='text-right font-medium'>
                      {'- ' + currencyFormat(totalDiscountAmount)}
                    </div>
                  </div>

                  <hr className='w-full border border-gray-100 mt-4 mb-4 self-stretch' />

                  <div className='w-1/4 grid grid-cols-2 gap-y-3 text-gray_r-12/80'>
                    <div className='text-right'>Subtotal</div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.amountUntaxed)}
                    </div>

                    <div className='text-right'>
                      PPN {((PPN - 1) * 100).toFixed(0)}%
                    </div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.amountTax)}
                    </div>

                    <div className='text-right'>Biaya Pengiriman</div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.deliveryAmount)}
                    </div>
                  </div>

                  <hr className='w-full border border-gray-100 mt-4 mb-4 self-stretch' />

                  <div className='w-1/4 grid grid-cols-2 gap-y-3 font-semibold'>
                    <div className='text-right'>Grand Total</div>
                    <div className='text-right'>
                      {currencyFormat(transaction.data?.amountTotal)}
                    </div>
                  </div>
                </div>
              )}

              {transaction?.data?.productsRejectLine.length > 0 && (
                <div className='text-h-sm font-semibold mt-10 mb-4'>
                  Rincian Produk Reject
                </div>
              )}
              {transaction?.data?.productsRejectLine.length > 0 && (
                <table className='table-data'>
                  <thead>
                    <tr>
                      <th>Nama Produk</th>
                      <th>Jumlah</th>
                      <th>Harga</th>
                      <th>Subtotal</th>
                    </tr>
                  </thead>
                  <tbody>
                    {transaction?.data?.productsRejectLine?.map((product) => (
                      <tr key={product.id}>
                        <td className='flex'>
                          <Link
                            href={createSlug(
                              '/shop/product/',
                              product?.parent.name,
                              product?.parent.id
                            )}
                            className='w-[20%] flex-shrink-0'
                          >
                            <Image
                              src={product?.parent?.image}
                              alt={product?.name}
                              className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                            />
                          </Link>
                          <div className='px-2 text-left'>
                            <Link
                              href={createSlug(
                                '/shop/product/',
                                product?.parent.name,
                                product?.parent.id
                              )}
                              className='line-clamp-2 leading-6 !text-gray_r-12 font-normal'
                            >
                              {product?.parent?.name}
                            </Link>
                            <div className='text-gray_r-11 mt-2'>
                              {product?.code}{' '}
                              {product?.attributes.length > 0
                                ? `| ${product?.attributes.join(', ')}`
                                : ''}
                            </div>
                          </div>
                        </td>
                        <td>{product.quantity}</td>
                        <td>
                          <div>
                            {currencyFormat(product.price.priceDiscount)}
                          </div>
                        </td>
                        <td className='flex justify-center'>
                          <NextImage
                            src={rejectImage}
                            alt='Reject'
                            width={90}
                            height={30}
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </DesktopView>
      </>
    )
  );
};

const SectionAddress = ({ address }) => {
  const [section, setSection] = useState({
    customer: false,
    invoice: false,
    shipping: false,
  });
  const toggleSection = (name) => {
    setSection({ ...section, [name]: !section[name] });
  };

  return (
    <>
      <SectionButton
        label='Detail Pelanggan'
        active={section.customer}
        toggle={() => toggleSection('customer')}
      />

      {section.customer && <SectionContent address={address?.customer} />}

      {/* Bagian shipping/invoice disembunyikan */}
    </>
  );
};

const SectionButton = ({ label, active, toggle }) => (
  <button
    className='p-4 font-medium flex justify-between w-full'
    onClick={toggle}
  >
    <span>{label}</span>
    {active ? (
      <ChevronUpIcon className='w-5' />
    ) : (
      <ChevronDownIcon className='w-5' />
    )}
  </button>
);

const SectionContent = ({ address }) => {
  let fullAddress = [];
  if (address?.street) fullAddress.push(address.street);
  if (address?.subDistrict?.name)
    fullAddress.push(toTitleCase(address.subDistrict.name));
  if (address?.district?.name)
    fullAddress.push(toTitleCase(address.district.name));
  if (address?.city?.name) fullAddress.push(toTitleCase(address.city.name));
  fullAddress = fullAddress.join(', ');

  return (
    <div className='flex flex-col gap-y-4 p-4 md:p-0 border-t border-gray_r-6 md:border-0'>
      <DescriptionRow label='Nama'>{address.name}</DescriptionRow>
      <DescriptionRow label='Email'>{address.email || '-'}</DescriptionRow>
      <DescriptionRow label='No Telepon'>
        {address.mobile || '-'}
      </DescriptionRow>
      <DescriptionRow label='Alamat'>{fullAddress}</DescriptionRow>
    </div>
  );
};

const DescriptionRow = ({ children, label }) => (
  <div className='grid grid-cols-2'>
    <span className='text-gray_r-11'>{label}</span>
    <span className='text-right leading-6'>{children}</span>
  </div>
);

export default Transaction;