import style from '../styles/product-detail.module.css';

import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect, useRef, useState, UIEvent } from 'react';

// Import komponen Chakra UI
import { 
  Button, 
  Tabs, 
  TabList, 
  TabPanels, 
  Tab, 
  TabPanel, 
  Table, 
  Tbody, 
  Tr, 
  Td,
  Th, 
  Thead,
  Box,
  Spinner,
  Center,
  Text
} from '@chakra-ui/react';

// Import Icons
import {
  AlertTriangle,
  MessageCircleIcon,
  Share2Icon,
  ExternalLink
} from 'lucide-react';

import { LazyLoadComponent } from 'react-lazy-load-image-component';

import useDevice from '@/core/hooks/useDevice';
import { getAuth } from '~/libs/auth';
import { whatsappUrl } from '~/libs/whatsappUrl';
import ProductPromoSection from '~/modules/product-promo/components/Section';
import { IProductDetail } from '~/types/product';
import { useProductDetail } from '../stores/useProductDetail';
import AddToWishlist from './AddToWishlist';
import Breadcrumb from './Breadcrumb';
import ProductImage from './Image';
import Information from './Information';
import PriceAction from './PriceAction';
import SimilarBottom from './SimilarBottom';
import SimilarSide from './SimilarSide';
import dynamic from 'next/dynamic';

import { gtagProductDetail } from '@/core/utils/googleTag';

type Props = {
  product: IProductDetail;
};

const RWebShare = dynamic(
  () => import('react-web-share').then((m) => m.RWebShare),
  { ssr: false }
);

const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST;

const ProductDetail = ({ product }: Props) => {
  const { isDesktop, isMobile } = useDevice();
  const router = useRouter();
  const [auth, setAuth] = useState<any>(null);
  
  // State Data dari Magento
  const [specsMatrix, setSpecsMatrix] = useState<any[]>([]); 
  const [upsellIds, setUpsellIds] = useState<number[]>([]);
  const [relatedIds, setRelatedIds] = useState<number[]>([]); 
  const [descriptionMap, setDescriptionMap] = useState<Record<string, string>>({});
  
  const [loadingSpecs, setLoadingSpecs] = useState(false);

  useEffect(() => {
    try {
      setAuth(getAuth() ?? null);
    } catch {}
  }, []);

  const canShare =
    typeof navigator !== 'undefined' &&
    typeof (navigator as any).share === 'function';

  const {
    setAskAdminUrl,
    askAdminUrl,
    activeVariantId,
    setIsApproval,
    isApproval,
    selectedVariant, 
    setSelectedVariant,
  } = useProductDetail();

  useEffect(() => {
    gtagProductDetail(product);
  }, [product]);

  useEffect(() => {
    const createdAskUrl = whatsappUrl({
      template: 'product',
      payload: {
        manufacture: product.manufacture.name,
        productName: product.name,
        url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath,
      },
      fallbackUrl: router.asPath,
    });

    setAskAdminUrl(createdAskUrl);
  }, [router.asPath, product.manufacture.name, product.name, setAskAdminUrl]);

  // =========================================================================
  // 1. LOGIC INISIALISASI VARIANT
  // =========================================================================
  useEffect(() => {
    if (typeof auth === 'object') {
      setIsApproval(auth?.feature?.soApproval);
    }
    const variantInit =
      product?.variants?.find((variant) => variant.is_in_bu) ||
      product?.variants?.[0];
    
    setSelectedVariant(variantInit);

    setSpecsMatrix([]);
    setUpsellIds([]);
    setRelatedIds([]);
    
  }, [product, auth]); 

  // =========================================================================
  // 2. LOGIC FETCH DATA
  // =========================================================================
  useEffect(() => {
    const fetchMagentoData = async () => {
      const allVariantIds = product.variants.map(v => v.id);
      
      if (allVariantIds.length === 0) return;

      const mainId = allVariantIds[0];

      setLoadingSpecs(true);
      
      try {
        const params = new URLSearchParams({
            skus: allVariantIds.join(','),
            main_sku: String(mainId)
        });

        const endpoint = `/api/magento-product?${params.toString()}`;

        const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) {
            setSpecsMatrix([]);
            setUpsellIds([]);
            setRelatedIds([]);
            return;
        }

        const data = await response.json();

        // 1. Specs Matrix (Processed Grouping)
        if (data.specsMatrix && Array.isArray(data.specsMatrix)) {
            const filteredMatrix = data.specsMatrix.filter((item: any) => {
            const code = item.code || '';
            return !code.includes('z_brand');
        });

        const processed = processMatrixData(filteredMatrix);
        setSpecsMatrix(processed);
        } else {
           setSpecsMatrix([]);
        }

        if (data.descriptions){
          setDescriptionMap(data.descriptions);
        }

        // 2. Upsell & Related
        if (data.upsell_ids && Array.isArray(data.upsell_ids)) setUpsellIds(data.upsell_ids);
        else setUpsellIds([]);

        if (data.related_ids && Array.isArray(data.related_ids)) setRelatedIds(data.related_ids);
        else setRelatedIds([]);

      } catch (error) {
        console.error("Gagal mengambil data Magento:", error);
        setSpecsMatrix([]);
      } finally {
        setLoadingSpecs(false);
      }
    };

    fetchMagentoData();

  }, [product.id]); 

  // =========================================================================
  // HELPER 1: GROUPING DATA BY LABEL (Separator ':')
  // =========================================================================
  const processMatrixData = (rawMatrix: any[]) => {
      const groups: any = {};
      const result: any[] = [];

      rawMatrix.forEach(item => {
          // Cek Label: "Group Name : Sub Label"
          if (item.label && item.label.includes(' : ')) {
              const parts = item.label.split(' : ');
              const groupName = parts[0].trim(); 
              const childLabel = parts.slice(1).join(' : ').trim();

              if (!groups[groupName]) {
                  groups[groupName] = {
                      type: 'group',
                      label: groupName,
                      children: []
                  };
                  result.push(groups[groupName]);
              }
              
              groups[groupName].children.push({
                  ...item,
                  label: childLabel // Override label jadi pendek
              });

          } else {
              result.push({ ...item, type: 'single' });
          }
      });

      return result;
  };


  // =========================================================================
  // HELPER 2: RENDER SPEC VALUE
  // =========================================================================
  const renderSpecValue = (val: any) => {
    if (!val) return '-';
    const strVal = String(val).trim();

    // URL Link
    const isUrl = !strVal.includes(' ') && (
      strVal.startsWith('http') || 
      strVal.startsWith('www.')
    );
    if (isUrl) {
      const href = strVal.startsWith('http') ? strVal : `https://${strVal}`;
      return (
        <a 
          href={href} 
          target="_blank" 
          rel="noopener noreferrer"
          className="text-red-600 hover:underline inline-flex items-center gap-1"
        >
          <ExternalLink size={14} /> Link
        </a>
      );
    }

    // HTML
    if (strVal.includes('<') && strVal.includes('>')) {
       return (
         <div 
           className="prose prose-sm text-gray-700"
           dangerouslySetInnerHTML={{ __html: strVal }}
         />
       );
    }

    // Teks Biasa
    return strVal;
  };


  const allImages = (() => {
    const arr: string[] = [];
    if (product?.image) arr.push(product.image);
    if (
      Array.isArray(product?.image_carousel) &&
      product.image_carousel.length
    ) {
      const set = new Set(arr);
      for (const img of product.image_carousel) {
        if (!set.has(img)) {
          arr.push(img);
          set.add(img);
        }
      }
    }
    return arr;
  })();

  const [mainImage, setMainImage] = useState(allImages[0] || '');
  const hasPrice = Number(product?.lowest_price?.price) > 0;

  useEffect(() => {
    if (!allImages.includes(mainImage)) {
      setMainImage(allImages[0] || '');
    }
  }, [allImages]);

  const sliderRef = useRef<HTMLDivElement | null>(null);
  const [currentIdx, setCurrentIdx] = useState(0);

  const handleMobileScroll = (e: UIEvent<HTMLDivElement>) => {
    const el = e.currentTarget;
    if (!el) return;
    const idx = Math.round(el.scrollLeft / el.clientWidth);
    if (idx !== currentIdx) {
      setCurrentIdx(idx);
      setMainImage(allImages[idx] || '');
    }
  };

  const scrollToIndex = (i: number) => {
    const el = sliderRef.current; 
    if (!el) return; 
    el.scrollTo({ left: i * el.clientWidth, behavior: 'smooth' });
    setCurrentIdx(i);
    setMainImage(allImages[i] || '');
  };

  const activeMagentoDesc = selectedVariant?.id ? descriptionMap[String(selectedVariant.id)] : '';
  const finalDescription = activeMagentoDesc || product.description || 'Deskripsi produk tidak tersedia.';
  const cleanDescription = finalDescription === '<p><br></p>' ? 'Deskripsi produk tidak tersedia.' : finalDescription;

  return (
    <>
      <div className='relative'>
        {isDesktop && !hasPrice && (
          <div className='absolute inset-0 z-[20] flex items-center justify-center pointer-events-none select-none'>
            <img
              src='/images/produk_tidak_tersedia.svg'
              alt='Produk tidak tersedia'
              className='w-[47%] opacity-50 -translate-x-[3%]  -translate-y-[-70%]'
            />
          </div>
        )}
      </div>

      <div className='relative'>
        {isMobile && !hasPrice && (
          <div className='absolute inset-0 z-[50] flex items-center justify-center pointer-events-none select-none'>
            <img
              src='/images/produk_tidak_tersedia.svg'
              alt='Produk tidak tersedia'
              className='w-[100%] opacity-[1000%] -translate-x-[0%]  -translate-y-[-197%]'
            />
          </div>
        )}
      </div>

      <div className='md:flex md:flex-wrap'>
        <div className='w-full mb-4 md:mb-0 px-4 md:px-0'>
          <Breadcrumb id={product.id} name={product.name} />
        </div>

        <div className='md:w-9/12 md:flex md:flex-col md:pr-4 md:pt-6'>
          <div className='md:flex md:flex-wrap'>
            {/* ===== Kolom kiri: gambar ===== */}
            <div className='md:w-4/12'>
              {/* ... Image Slider ... */}
              {isMobile ? (
                <div className='relative'>
                  <div ref={sliderRef} onScroll={handleMobileScroll} className='flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar' style={{ scrollBehavior: 'smooth', msOverflowStyle: 'none', scrollbarWidth: 'none' }}>
                    {allImages.length > 0 ? (
                      allImages.map((img, i) => (
                        <div key={i} className='w-full flex-shrink-0 snap-center flex justify-center items-center'>
                          <img src={img} alt={`Gambar ${i + 1}`} className='w-[85%] aspect-square object-contain' onError={(e) => { (e.target as HTMLImageElement).src = '/images/noimage.jpeg'; }} />
                        </div>
                      ))
                    ) : (
                      <div className='w-full flex-shrink-0 snap-center flex justify-center items-center'>
                        <img src={mainImage || '/images/noimage.jpeg'} alt='Gambar produk' className='w-[85%] aspect-square object-contain' />
                      </div>
                    )}
                  </div>
                  {allImages.length > 1 && (
                    <div className='absolute bottom-2 left-0 right-0 flex justify-center gap-2'>
                      {allImages.map((_, i) => (
                        <button key={i} aria-label={`Ke slide ${i + 1}`} className={`w-2 h-2 rounded-full ${currentIdx === i ? 'bg-gray-800' : 'bg-gray-300'}`} onClick={() => scrollToIndex(i)} />
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <>
                  <ProductImage product={{ ...product, image: mainImage }} />
                  {allImages.length > 0 && (
                    <div className='mt-4 overflow-x-auto'>
                      <div className='flex space-x-3 pb-3'>
                        {allImages.map((img, index) => (
                          <div key={index} className={`flex-shrink-0 w-16 h-16 cursor-pointer border-2 rounded-md transition-colors ${mainImage === img ? 'border-red-500 ring-2 ring-red-200' : 'border-gray-200 hover:border-gray-300'}`} onClick={() => setMainImage(img)}>
                            <img src={img} alt={`Thumbnail ${index + 1}`} className='w-full h-full object-cover rounded-sm' loading='lazy' onError={(e) => { (e.target as HTMLImageElement).src = '/images/noimage.jpeg'; }} />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* ===== Kolom kanan: info ===== */}
            {isDesktop && (
              <div className='md:w-8/12 px-4 md:pl-6'>
                {!hasPrice && (
                  <div className='bg-red-50 p-2 py-1.5 rounded-lg border border-red-500 flex gap-1 items-center '>
                    <AlertTriangle size={18} className='text-red-600 shrink-0 mx-2' />
                    <h1 className='text-red-600 font-normal text-h-sm'>Maaf untuk saat ini Produk yang anda cari tidak tersedia</h1>
                  </div>
                )}
                <div className='h-6 md:h-0' />
                <h1 className={style['title']}>{product.name}</h1>
                <div className='h-3 md:h-0' />
                <Information product={product} />
                <div className='h-6' />
              </div>
            )}
            {isMobile && (
              <div className='md:w-8/12 px-4 md:pl-6 relative'>
                {!hasPrice && (
                  <div className='bg-red-50 p-2 py-1.5 border-b border-red-500 flex gap-1 items-center w-screen relative left-1/2 right-1/2 -translate-x-1/2'>
                    <AlertTriangle size={18} className='text-red-600 shrink-0 mx-2' />
                    <h1 className='text-red-600 font-normal text-h-sm'>Maaf untuk saat ini Produk yang anda cari tidak tersedia</h1>
                  </div>
                )}
                <h1 className={style['title']}>{product.name}</h1>
                <div className='h-3 md:h-0' />
                <Information product={product} />
                <div className='h-6' />
              </div>
            )}
          </div>

          <div className='h-full'>
            {isMobile && (
              <div className='px-4 pt-6'>
                <PriceAction product={product} />
              </div>
            )}

            <div className='h-4 md:h-10' />
            {!!activeVariantId && !isApproval && (
              <ProductPromoSection product={product} productId={activeVariantId} />
            )}

            <div className='h-0 md:h-6' />

            {/* === SECTION TABS: DESKRIPSI & SPESIFIKASI === */}
            <div className={style['section-card']}>
              <Tabs variant="unstyled">
                <TabList borderBottom="1px solid" borderColor="gray.200">
                  <Tab _selected={{ color: 'red.600', borderColor: 'red.600', borderBottomWidth: '3px', fontWeight: 'bold', marginBottom: '-1.5px' }} color="gray.500" fontWeight="medium" fontSize="sm" px={4} py={3}>Deskripsi</Tab>
                  <Tab _selected={{ color: 'red.600', borderColor: 'red.600', borderBottomWidth: '3px', fontWeight: 'bold', marginBottom: '-1.5px' }} color="gray.500" fontWeight="medium" fontSize="sm" px={4} py={3}>Spesifikasi</Tab>
                  <Tab _selected={{ color: 'red.600', borderColor: 'red.600', borderBottomWidth: '3px', fontWeight: 'bold', marginBottom: '-1.5px' }} color="gray.500" fontWeight="medium" fontSize="sm" px={4} py={3}>Detail Lainnya</Tab>
                </TabList>

                <TabPanels>
                  {/* DESKRIPSI */}
                  <TabPanel px={0} py={6}>
                    <div className='overflow-x-auto text-sm text-gray-700'>
                      <div className={style['description']} dangerouslySetInnerHTML={{ __html: cleanDescription }} />
                    </div>
                  </TabPanel>

                  {/* SPESIFIKASI */}
                  <TabPanel px={0} py={2}>
                    <Box 
                      border="1px solid" 
                      borderColor="gray.200" 
                      borderRadius="sm" 
                      overflowX="auto"
                      overflowY="auto"   
                      maxHeight="500px"  
                      css={{
                        '&::-webkit-scrollbar': {
                          width: '12px',  
                          height: '12px', 
                        },
                        '&::-webkit-scrollbar-track': {
                          background: '#f1f1f1',
                        },
                        '&::-webkit-scrollbar-thumb': {
                          backgroundColor: '#a0aec0', 
                          borderRadius: '8px',
                          border: '4px solid transparent',
                          backgroundClip: 'content-box',
                        },
                        '&::-webkit-scrollbar-thumb:hover': {
                          backgroundColor: '#718096', 
                        },
                      }}
                    >
                      {loadingSpecs ? (
                        <Center py={6}><Spinner color='red.500' /></Center>
                      ) : specsMatrix.length > 0 ? (
                        (() => {
                          const topHeaders: any[] = [];
                          const subHeaders: any[] = [];
                          const flatSpecs: any[] = [];

                          specsMatrix.forEach(row => {
                            if (row.type === 'group') {
                                topHeaders.push({ 
                                    label: row.label, 
                                    type: 'group', 
                                    colSpan: row.children.length, 
                                    rowSpan: 1 
                                });
                                row.children.forEach((child: any) => {
                                    subHeaders.push(child);
                                    flatSpecs.push(child);
                                });
                            } else {
                                topHeaders.push({ 
                                    label: row.label, 
                                    type: 'single', 
                                    colSpan: 1, 
                                    rowSpan: 2 
                                });
                                flatSpecs.push(row);
                            }
                          });

                          return (
                            <Table variant="simple" size="md">
                              <Thead bg="red.600" position="sticky" top={0} zIndex={20}>
                                <Tr>
                                  <Th 
                                    position="sticky" left={0} top={0} zIndex={21} bg="red.600"
                                    rowSpan={2}
                                    width="25%" 
                                    minW="100px" 
                                    borderColor="whiteAlpha.300" color="white" 
                                    fontSize="sm" textTransform="none" verticalAlign="middle"
                                    textAlign="center"
                                    boxShadow="2px 0 5px -2px rgba(0,0,0,0.1)"
                                  >
                                    Variant
                                  </Th>

                                  {topHeaders.map((th, idx) => (
                                    <Th 
                                      key={`top-${idx}`}
                                      position="sticky" top={0} zIndex={20} bg="red.600" 
                                      colSpan={th.colSpan}
                                      rowSpan={th.rowSpan}
                                      // borderColor="whiteAlpha.300" 
                                      color="white" 
                                      textAlign="center" 
                                      fontSize="sm" 
                                      textTransform="none" 
                                      fontWeight="800"
                                      letterSpacing="wide"
                                      verticalAlign="middle"
                                    >
                                      {th.label}
                                    </Th>
                                  ))}
                                </Tr>
                                <Tr>
                                  {subHeaders.map((sub, idx) => (
                                    <Th 
                                      key={`sub-${idx}`}
                                      // borderColor="whiteAlpha.300" 
                                      color="white" 
                                      textAlign="center" 
                                      fontSize="xs"
                                      textTransform="none" 
                                      verticalAlign="middle"
                                      whiteSpace="nowrap"
                                      bg="red.600"
                                      pt={1} pb={1}
                                    >
                                      {sub.label}
                                    </Th>
                                  ))}
                                </Tr>
                              </Thead>
                              
                              <Tbody>
                                {product.variants.map((v, vIdx) => (
                                  <Tr key={v.id} bg={vIdx % 2 === 0 ? 'white' : 'gray.50'}>
                                    {/* 1. KOLOM JUDUL VARIANT (Sticky Kiri) */}
                                    <Td 
                                      position="sticky" left={0} zIndex={15} 
                                      bg={vIdx % 2 === 0 ? 'white' : 'gray.50'}
                                      fontWeight="bold" borderColor="gray.200" fontSize="sm" 
                                      verticalAlign="middle"
                                      boxShadow="2px 0 5px -2px rgba(0,0,0,0.05)"
                                      minW="100px"         
                                      textAlign="center"
                                      whiteSpace="normal" 
                                      py={4}               
                                    >
                                      {v.attributes && v.attributes.length > 0 ? v.attributes.join(' - ') : v.code}
                                    </Td>
                                    {/* 2. KOLOM DATA SPESIFIKASI */}
                                    {flatSpecs.map((spec, sIdx) => {
                                      const rawValue = spec.values[v.id] || '-';
                                      return (
                                        <Td 
                                          key={sIdx} 
                                          borderColor="gray.200" 
                                          textAlign="center" 
                                          fontSize="sm" 
                                          verticalAlign="middle"
                                          px={2}
                                          py={3} 
                                          minW="100px"   
                                          maxW="150px"        
                                          whiteSpace="normal" 
                                          overflowWrap="break-word"
                                        >
                                          {renderSpecValue(rawValue)}
                                        </Td>
                                      );
                                    })}
                                  </Tr>
                                ))}
                              </Tbody>
                            </Table>
                          );
                        })()
                      ) : (
                        <Box p={4} color="gray.500" fontSize="sm"><Text>Spesifikasi teknis belum tersedia.</Text></Box>
                      )}
                    </Box>
                  </TabPanel>
                  
                   {/* DETAIL LAINNYA */}
                   <TabPanel px={0} py={6}><p className="text-gray-500 text-sm">Informasi tambahan belum tersedia.</p></TabPanel>
                </TabPanels>
              </Tabs>
            </div>
          </div>
        </div>

        {/* ... (Bagian Sidebar & Bottom SAMA) ... */}
        {isDesktop && (
          <div className='md:w-3/12'>
            <PriceAction product={product} />
            <div className='flex gap-x-5 items-center justify-center py-4'>
                {/* ... Buttons ... */}
            </div>
            <div className='h-6' />
            <div className={style['heading']}>Produk Serupa</div>
            <div className='h-4' />
            <SimilarSide product={product} relatedIds={relatedIds} />
          </div>
        )}

        <div className='md:w-full pt-4 md:py-10 px-4 md:px-0'>
          <div className={style['heading']}>Kamu Mungkin Juga Suka</div>
          <div className='h-6' />
          <LazyLoadComponent>
            <SimilarBottom product={product} upsellIds={upsellIds} />
          </LazyLoadComponent>
        </div>
        <div className='h-6 md:h-0' />
      </div>
    </>
  );
};

export default ProductDetail;