summaryrefslogtreecommitdiff
path: root/src-migrate/modules/product-detail/components/ProductComparisonModal.tsx
blob: a58ad5b2a453ae995e7a32e6edec3678c9a44f5b (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
import React, { useEffect, useState } from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalCloseButton,
  Button,
  Text,
  Box,
  Badge,
  Grid,
  GridItem,
  Image,
  Input,
  InputGroup,
  InputLeftElement,
  VStack,
  HStack,
  IconButton,
  Flex,
  Icon,
  Spinner,
  List,
  ListItem,
  useToast,
  Select 
} from '@chakra-ui/react';

import { Search, ShoppingCart, Trash2 } from 'lucide-react';

// --- HELPER FORMATTING ---
const formatPrice = (price: number) => {
  return new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    minimumFractionDigits: 0,
  }).format(price);
};

const renderSpecValue = (val: any) => {
    if (!val || val === '-') return '-';
    return String(val).replace(/<[^>]*>?/gm, ''); 
};

type Props = {
  isOpen: boolean;
  onClose: () => void;
  mainProduct: any;     
  selectedVariant: any; 
};

const ProductComparisonModal = ({ isOpen, onClose, mainProduct, selectedVariant }: Props) => {
  const toast = useToast();
  
  // --- STATE ---
  const [products, setProducts] = useState<(any | null)[]>([null, null, null, null]);
  const [specsMatrix, setSpecsMatrix] = useState<any[]>([]);
  const [isLoadingMatrix, setIsLoadingMatrix] = useState(false);

  // Search State
  const [activeSearchSlot, setActiveSearchSlot] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  // ===========================================================================
  // 1. LOGIC UTAMA: ISI SLOT 1
  // ===========================================================================
  useEffect(() => {
    if (isOpen && mainProduct) {
      let activeItem = selectedVariant;
      
      if (!activeItem && mainProduct.variants && mainProduct.variants.length > 0) {
          activeItem = mainProduct.variants[0];
      }
      if (!activeItem) {
          activeItem = mainProduct;
      }

      const targetId = activeItem.id;
      const displayCode = activeItem.default_code || activeItem.code || activeItem.sku || mainProduct.default_code || mainProduct.code;

      const variantOptions = mainProduct.variants?.map((v: any) => ({
          id: v.id,
          code: v.default_code || v.code || v.sku, 
          name: v.name,
          price: v.price?.price || v.price || 0,
          image: v.image
      })) || [];

      if (variantOptions.length === 0) {
          variantOptions.push({
              id: targetId,
              code: displayCode,
              name: mainProduct.name,
              price: activeItem.price?.price || activeItem.price || 0,
              image: activeItem.image || mainProduct.image
          });
      }

      const productSlot1 = {
         id: targetId,
         sku: targetId, // ID untuk API
         realCode: displayCode, 
         name: mainProduct.name, 
         price: activeItem.price?.price || activeItem.price || mainProduct.lowest_price?.price || 0,
         image: activeItem.image || mainProduct.image,
         variants: variantOptions
      };

      setProducts((prev) => {
         const newSlots = [...prev];
         if (!newSlots[0] || String(newSlots[0].id) !== String(targetId)) {
             newSlots[0] = productSlot1;
         }
         return newSlots;
      });
    }
  }, [isOpen, mainProduct, selectedVariant]);

  // ===========================================================================
  // 2. FETCH SPECS
  // ===========================================================================
  useEffect(() => {
    const validProducts = products.filter(p => p !== null);
    if (!isOpen || validProducts.length === 0) return;

    const fetchSpecs = async () => {
        setIsLoadingMatrix(true);
        try {
            const allSkus = validProducts.map(p => p.sku).join(',');
            const mainSku = validProducts[0]?.sku;

            const res = await fetch(`/api/magento-product?skus=${allSkus}&main_sku=${mainSku}`);
            if (!res.ok) return;

            const data = await res.json();
            if (data.specsMatrix) {
                setSpecsMatrix(data.specsMatrix);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoadingMatrix(false);
        }
    };

    fetchSpecs();
  }, [products, isOpen]);

  // ===========================================================================
  // 3. SEARCH LOGIC
  // ===========================================================================
  useEffect(() => {
     const delayDebounceFn = setTimeout(async () => {
        if (searchQuery.length < 3) {
            setSearchResults([]);
            return;
        }

        setIsSearching(true);
        try {
            const attrSetId = selectedVariant?.attribute_set_id || mainProduct?.attribute_set_id;
            const params = new URLSearchParams({
                source: 'compare',
                q: searchQuery,
                limit: '5',
                fq: attrSetId ? `attribute_set_id_i:${attrSetId}` : ''
            });

            const res = await fetch(`/api/search?${params.toString()}`);
            if (res.ok) {
                const data = await res.json();
                setSearchResults(data.response?.products || []);
            } else {
                setSearchResults([]);
            }
        } catch (e) {
            setSearchResults([]);
        } finally {
            setIsSearching(false);
        }
     }, 500);

     return () => clearTimeout(delayDebounceFn);
  }, [searchQuery, mainProduct, selectedVariant]);

  // ===========================================================================
  // 4. HANDLERS
  // ===========================================================================
  const handleVariantChange = (slotIndex: number, newId: string) => {
      const currentProduct = products[slotIndex];
      if (!currentProduct || !currentProduct.variants) return;

      const selectedVar = currentProduct.variants.find((v: any) => String(v.id) === String(newId));
      
      if (selectedVar) {
          const newProducts = [...products];
          newProducts[slotIndex] = {
              ...currentProduct,
              id: selectedVar.id,
              sku: selectedVar.id, 
              realCode: selectedVar.code,
              price: selectedVar.price,
              image: selectedVar.image
          };
          setProducts(newProducts);
      }
  };

  const handleAddProduct = (solrProduct: any, slotIndex: number) => {
      const newProducts = [...products];
      
      const idToAdd = solrProduct.product_id_i || solrProduct.id;
      const codeToAdd = solrProduct.default_code_s || solrProduct.sku;

      if (newProducts.find(p => p && String(p.id) === String(idToAdd))) {
          toast({ title: "Produk sudah ada", status: "warning", position: "top" });
          return;
      }

      newProducts[slotIndex] = {
          id: idToAdd,
          sku: idToAdd, 
          realCode: codeToAdd,
          name: solrProduct.display_name_s || solrProduct.name_s,
          price: solrProduct.price_tier1_v2_f || 0,
          image: solrProduct.image_s,
          variants: [{
              id: idToAdd,
              code: codeToAdd,
              name: solrProduct.name_s,
              price: solrProduct.price_tier1_v2_f,
              image: solrProduct.image_s
          }]
      };

      setProducts(newProducts);
      setActiveSearchSlot(null);
      setSearchQuery('');
      setSearchResults([]);
  };

  const handleRemoveProduct = (index: number) => {
      const newProducts = [...products];
      newProducts[index] = null;
      setProducts(newProducts);
      if (newProducts.every(p => p === null)) setSpecsMatrix([]);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="6xl" scrollBehavior="inside">
      <ModalOverlay />
      <ModalContent height="90vh">
        <ModalHeader borderBottom="1px solid #eee" pb={2}>
          <HStack spacing={3}>
            <Text fontSize="xl" fontWeight="bold">Bandingkan Produk</Text>
            <Badge colorScheme="red" variant="solid" borderRadius="full" px={2}>
              {products.filter(p => p !== null).length} Item
            </Badge>
          </HStack>
          <Text fontSize="sm" color="gray.500" fontWeight="normal" mt={1}>
             Detail Spesifikasi Produk yang kamu pilih
          </Text>
        </ModalHeader>
        <ModalCloseButton />

        <ModalBody p={6} bg="white">
          <Grid templateColumns="200px repeat(4, 1fr)" gap={4}>
            
            {/* Cell 1: Kosong */}
            <GridItem />

            {/* Loop Slot Produk */}
            {products.map((product, index) => (
              <GridItem key={index} position="relative" minW="0">
                {product ? (
                  <VStack align="stretch" spacing={3} h="100%">
                    
                    {/* Tombol Hapus */}
                    {index !== 0 && (
                        <IconButton 
                            aria-label="Hapus" icon={<Trash2 size={16}/>} 
                            size="xs" position="absolute" top={-2} right={-2} 
                            colorScheme="red" onClick={() => handleRemoveProduct(index)} zIndex={2}
                        />
                    )}

                    {/* Gambar */}
                    <Box h="160px" display="flex" alignItems="center" justifyContent="center" bg="gray.50" borderRadius="md" p={2}>
                      <Image 
                        src={product.image || '/images/noimage.jpeg'} 
                        alt={product.name} 
                        maxH="100%" objectFit="contain" 
                        onError={(e) => { (e.target as HTMLImageElement).src = '/images/noimage.jpeg'; }}
                      />
                    </Box>

                    {/* Info Harga & Nama */}
                    <Box>
                      <Text color="red.600" fontWeight="bold" fontSize="md">
                        {product.price > 0 ? formatPrice(product.price) : 'Hubungi Admin'}
                      </Text>
                      {/* Margin Bottom agar tidak tertutup dropdown */}
                      <Text fontSize="xs" fontWeight="bold" noOfLines={2} h="35px" title={product.name} mb={2}>
                        {product.name}
                      </Text>
                    </Box>

                    {/* Dropdown Varian */}
                    <Select 
                        size="sm" 
                        borderRadius="md" 
                        fontSize="xs"
                        value={product.id} 
                        onChange={(e) => handleVariantChange(index, e.target.value)}
                        isDisabled={false} 
                        bg="white"
                    >
                        {product.variants && product.variants.map((v: any) => (
                            <option key={v.id} value={v.id}>
                                {v.code}
                            </option>
                        ))}
                    </Select>

                    {/* Tombol */}
                    <HStack spacing={2}>
                        <IconButton aria-label="Cart" icon={<Icon as={ShoppingCart} />} variant="outline" colorScheme="red" size="sm" />
                        <Button as="a" href={`/product/${product.id}`} target="_blank" colorScheme="red" size="sm" flex={1} fontSize="xs">
                            Lihat Detail
                        </Button>
                    </HStack>
                  </VStack>
                ) : (
                  // SLOT KOSONG
                  <VStack align="stretch" spacing={3} h="100%" position="relative">
                     <InputGroup size="sm">
                      <InputLeftElement pointerEvents="none"><Icon as={Search} color="gray.300" /></InputLeftElement>
                      <Input 
                        placeholder="Cari Produk..." borderRadius="md" 
                        value={activeSearchSlot === index ? searchQuery : ''}
                        onFocus={() => { setActiveSearchSlot(index); setSearchQuery(''); }}
                        onChange={(e) => setSearchQuery(e.target.value)}
                      />
                    </InputGroup>

                    {activeSearchSlot === index && searchQuery.length > 0 && (
                        <Box position="absolute" top="35px" left={0} right={0} bg="white" boxShadow="lg" zIndex={10} borderRadius="md" border="1px solid" borderColor="gray.200" maxH="250px" overflowY="auto">
                            {isSearching ? (
                                <Box p={4} textAlign="center"><Spinner size="sm" color="red.500"/></Box>
                            ) : searchResults.length > 0 ? (
                                <List spacing={0}>
                                    {searchResults.map((res) => (
                                        <ListItem 
                                            key={res.product_id_i || res.id} 
                                            p={2} borderBottom="1px solid #f0f0f0" 
                                            _hover={{ bg: 'red.50', cursor: 'pointer' }}
                                            onClick={() => handleAddProduct(res, index)}
                                        >
                                            <Flex align="center" gap={2}>
                                                <Image src={res.image_s || '/images/noimage.jpeg'} boxSize="30px" objectFit="contain" onError={(e) => { (e.target as HTMLImageElement).src = '/images/noimage.jpeg'; }} />
                                                <Box>
                                                    <Text fontSize="xs" fontWeight="bold" noOfLines={1}>{res.display_name_s || res.name_s}</Text>
                                                    <Text fontSize="xs" color="red.500">{formatPrice(res.price_tier1_v2_f || 0)}</Text>
                                                </Box>
                                            </Flex>
                                        </ListItem>
                                    ))}
                                </List>
                            ) : (
                                <Box p={3} fontSize="xs" color="gray.500" textAlign="center">Tidak ditemukan.</Box>
                            )}
                        </Box>
                    )}
                    
                    <Flex direction="column" align="center" justify="center" flex={1} border="2px dashed" borderColor="gray.200" borderRadius="md" bg="gray.50" color="gray.400">
                        <Icon as={Search} w={8} h={8} opacity={0.3} mb={2} />
                        <Text fontSize="xs" textAlign="center">Tambah produk<br/>untuk membandingkan</Text>
                    </Flex>
                  </VStack>
                )}
              </GridItem>
            ))}

            {/* --- BAGIAN SPESIFIKASI --- */}
            <GridItem colSpan={5} py={6}>
               <Box borderBottom="2px solid" borderColor="gray.100" pb={2}>
                  <Text fontSize="lg" fontWeight="bold">Spesifikasi Teknis</Text>
               </Box>
            </GridItem>

            {isLoadingMatrix ? (
                 <GridItem colSpan={5} textAlign="center" py={10}>
                     <Spinner color="red.500" thickness="4px" size="xl" />
                     <Text mt={2} color="gray.500">Memuat data...</Text>
                 </GridItem>
            ) : specsMatrix.length > 0 ? (
                specsMatrix.map((row, rowIndex) => (
                  <React.Fragment key={row.code || rowIndex}>
                    {/* Label (Kiri) */}
                    <GridItem 
                        py={3} 
                        px={2}
                        borderBottom="1px solid" 
                        borderColor="gray.100" 
                        bg={rowIndex % 2 !== 0 ? "white" : "gray.50"}
                        display="flex"
                        alignItems="center"
                    >
                      <Text fontWeight="bold" fontSize="sm" color="gray.700">{row.label}</Text>
                    </GridItem>

                    {/* Value (Rata Tengah) */}
                    {products.map((product, colIndex) => {
                        const val = product ? (row.values[String(product.sku)] || '-') : '';
                        
                        return (
                          <GridItem 
                            key={`${row.code}-${colIndex}`} 
                            py={3} 
                            px={2}
                            borderBottom="1px solid" 
                            borderColor="gray.100" 
                            bg={rowIndex % 2 !== 0 ? "white" : "gray.50"}
                            display="flex" // [FIX] Flex untuk centering
                            alignItems="center" // [FIX] Vertical Center
                            justifyContent="center" // [FIX] Horizontal Center
                            textAlign="center" // [FIX] Text Align Center
                          >
                            <Text fontSize="sm" color="gray.600">{renderSpecValue(val)}</Text>
                          </GridItem>
                        );
                    })}
                  </React.Fragment>
                ))
            ) : (
                <GridItem colSpan={5} py={10} textAlign="center" color="gray.500" bg="gray.50">
                    <Text>Data spesifikasi belum tersedia untuk produk ini.</Text>
                </GridItem>
            )}

          </Grid>
        </ModalBody>
      </ModalContent>
    </Modal>
  );
};

export default ProductComparisonModal;