import { Box, Button, Skeleton, Tooltip } from '@chakra-ui/react';
import { HeartIcon } from '@heroicons/react/24/outline';
import { Info, MessageCircleIcon, Share2Icon } from 'lucide-react';
import { useRouter } from 'next/router';
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'react-hot-toast';
import AddToWishlist from '../../../../../src-migrate/modules/product-detail/components/AddToWishlist';
import { RWebShare } from 'react-web-share';
import LazyLoad from 'react-lazy-load';
import { useProductCartContext } from '@/contexts/ProductCartContext';
import odooApi from '@/core/api/odooApi';
import Image from '@/core/components/elements/Image/Image';
import Link from '@/core/components/elements/Link/Link';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import DesktopView from '@/core/components/views/DesktopView';
import useAuth from '@/core/hooks/useAuth';
import { updateItemCart } from '@/core/utils/cart';
import currencyFormat from '@/core/utils/currencyFormat';
import { createSlug } from '@/core/utils/slug';
import whatsappUrl from '@/core/utils/whatsappUrl';
import { getAuth } from '~/libs/auth';

import ImageNext from 'next/image';
import productSimilarApi from '../../api/productSimilarApi';
import ProductCard from '../ProductCard';
import ProductSimilar from '../ProductSimilar';
import ProductPromoSection from '~/modules/product-promo/components/Section';
import SimilarBottom from '~/modules/product-detail/components/SimilarBottom';
import { gtagAddToCart } from '@/core/utils/googleTag';
const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST;

const ProductDesktopVariant = ({
  product,
  wishlist,
  toggleWishlist,
  isVariant,
}) => {
  const router = useRouter();
  let auth = useAuth();
  const { slug } = router.query;
  const { srsltid } = router.query;
  const [askAdminUrl, setAskAdminUrl, isApproval] = useState();
  const [lowestPrice, setLowestPrice] = useState(null);
  const [qtyPickUp, setQtyPickUp] = useState(0);
  const [addCartAlert, setAddCartAlert] = useState(false);
  const [isLoadingSLA, setIsLoadingSLA] = useState(true);
  const [selectedVariant, setSelectedVariant] = useState(product.id);
  const { setRefreshCart } = useProductCartContext();

  const [quantityInput, setQuantityInput] = useState(1);

  const [activeVariant, setActiveVariant] = useState({
    id: null,
    code: product.code,
    name: product.name,
    price: lowestPrice,
    stock: product.stockTotal,
    weight: product.weight,
    isFlashSale: product.isFlashSale,
  });

  useEffect(() => {
    if (selectedVariant) {
      setActiveVariant({
        id: product.id,
        code: product.code,
        name: product.name,
        price: product.price,
        stock: product.stockTotal,
        weight: product.weight,
        isFlashSale: product.isFlashSale,
      });
    }
  }, [selectedVariant, product]);

  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,
  });

  const getLowestPrice = useCallback(() => {
    const lowest = product.price;
    return lowest;
  }, [product]);

  useEffect(() => {
    const lowest = getLowestPrice();
    setLowestPrice(lowest);
  }, [getLowestPrice]);

  const [informationTab, setInformationTab] = useState(
    informationTabOptions[0].value
  );

  const variantQuantityRefs = useRef([]);

  const setVariantQuantityRef = (variantId) => (element) => {
    variantQuantityRefs.current[variantId] = element;
  };

  const handleAddToCart = (variant) => {
    if (!auth) {
      router.push(`/login?next=/shop/product/${slug}?srsltid=${srsltid}`);
      return;
    }
    const quantity = quantityInput;
    if (!validQuantity(quantity)) return;
    gtagAddToCart(activeVariant, quantity);
    updateItemCart({
      productId: product.id,
      quantity,
      programLineId: null,
      selected: true,
      source: null,
    }).then(() => {
      setRefreshCart(true);
    });
    setAddCartAlert(true);
  };

  const toInt = (v) => {
    const n = parseInt(String(v ?? '').trim(), 10);
    return Number.isFinite(n) ? n : 0;
  };

  const validQuantity = (q) => {
    if (!Number.isInteger(q) || q < 1) {
      toast.error('Jumlah barang minimal 1');
      return false;
    }
    return true;
  };

  const handleBuy = async (variant) => {
    const quantity = Math.max(1, toInt(quantityInput)); // clamp min 1

    let isLoggedIn = typeof auth === 'object';
    if (!isLoggedIn) {
      const currentUrl = encodeURIComponent(router.asPath);
      await router.push(`/login?next=${currentUrl}`);

      // tunggu sampai auth ada
      await new Promise((resolve) => {
        const t = setInterval(() => {
          const newAuth = getAuth();
          if (typeof newAuth === 'object') {
            isLoggedIn = true;
            auth = newAuth;
            clearInterval(t);
            resolve();
          }
        }, 500);
      });
    }

    if (!validQuantity(quantity)) return;

    await updateItemCart({
      productId: variant,
      quantity,
      programLineId: null,
      selected: true,
      source: 'buy',
    });

    router.push('/shop/checkout?source=buy');
  };

  // const handleBuy = async (variant) => {
  //   const quantity = variantQuantityRefs?.current[product.id]?.value;
  //   let isLoggedIn = typeof auth === 'object';

  //   if (!isLoggedIn) {
  //     const currentUrl = encodeURIComponent(router.asPath);
  //     await router.push(`/login?next=${currentUrl}`);

  //     // Tunggu login berhasil, misalnya dengan memantau perubahan status auth.
  //     const authCheckInterval = setInterval(() => {
  //       const newAuth = getAuth();
  //       if (typeof newAuth === 'object') {
  //         isLoggedIn = true;
  //         auth = newAuth; // Update nilai auth setelah login
  //         clearInterval(authCheckInterval);
  //       }
  //     }, 500); // Periksa status login setiap 500ms

  //     await new Promise((resolve) => {
  //       const checkLogin = setInterval(() => {
  //         if (isLoggedIn) {
  //           clearInterval(checkLogin);
  //           resolve(null);
  //         }
  //       }, 500);
  //     });
  //   }

  //   if (!validQuantity(quantity)) return;

  //   updateItemCart({
  //     productId: variant,
  //     quantity,
  //     programLineId: null,
  //     selected: true,
  //     source: 'buy',
  //   });
  //   router.push(`/shop/checkout?source=buy`);
  // };

  const handleButton = async (variant) => {
    const quantity = quantityInput;
    let isLoggedIn = typeof auth === 'object';

    if (!isLoggedIn) {
      const currentUrl = encodeURIComponent(router.asPath);
      await router.push(`/login?next=${currentUrl}`);

      // Tunggu login berhasil, misalnya dengan memantau perubahan status auth.
      const authCheckInterval = setInterval(() => {
        const newAuth = getAuth();
        if (typeof newAuth === 'object') {
          isLoggedIn = true;
          auth = newAuth; // Update nilai auth setelah login
          clearInterval(authCheckInterval);
        }
      }, 500); // Periksa status login setiap 500ms

      await new Promise((resolve) => {
        const checkLogin = setInterval(() => {
          if (isLoggedIn) {
            clearInterval(checkLogin);
            resolve(null);
          }
        }, 500);
      });
    }
    if (!validQuantity(quantity)) return;

    updateItemCart({
      productId: variant,
      quantity,
      programLineId: null,
      selected: true,
      source: 'buy',
    });
    router.push('/shop/quotation?source=buy');
  };

  const variantSectionRef = useRef(null);
  const goToVariantSection = () => {
    if (variantSectionRef.current) {
      const position = variantSectionRef.current.getBoundingClientRect();
      window.scrollTo({
        top: position.top - 120 + window.pageYOffset,
        behavior: 'smooth',
      });
    }
  };

  const productSimilarQuery = [
    product?.name,
    `fq=-product_id_i:${product.id}`,
    `fq=-manufacture_id_i:${product.manufacture?.id || 0}`,
  ].join('&');

  const [productSimilarInBrand, setProductSimilarInBrand] = useState(null);

  useEffect(() => {
    const loadProductSimilarInBrand = async () => {
      const productSimilarQuery = [
        product?.name,
        `fq=-product_id_i:${product.id}`,
      ].join('&');
      const dataProductSimilar = await productSimilarApi({
        query: productSimilarQuery,
      });
      setProductSimilarInBrand(dataProductSimilar.products);
    };
    if (!productSimilarInBrand) loadProductSimilarInBrand();
  }, [product, productSimilarInBrand]);

  useEffect(() => {
    const fetchData = async () => {
      const dataSLA = await odooApi(
        'GET',
        `/api/v1/product_variant/${product.id}/stock`
      );
      product.sla = dataSLA;

      setIsLoadingSLA(false);
    };
    fetchData();
  }, [product]);

  useEffect(() => {
    const fetchData = async () => {
      const qty_available = await odooApi(
        'GET',
        `/api/v1/product_variant/${product.id}/qty_available`
      );
      setQtyPickUp(qty_available?.qty);
    };
    fetchData();
  }, [product]);

  return (
    <DesktopView>
      <div className='container mx-auto pt-10'>
        <div className='flex'>
          <div className='w-full flex flex-wrap'>
            <div className='w-5/12'>
              <Image
                src={product.image + '?variant=True'}
                alt={product.name}
                className='w-full h-[350px]'
              />
            </div>

            <div className='w-7/12 px-6'>
              <h1 className='text-title-md leading-10 font-medium'>
                {product?.name}
              </h1>
              <div className='mt-10'>
                <div className='flex p-3 bg-gray_r-4'>
                  <div className='w-4/12 text-gray_r-12/70'>Item Code</div>
                  <div className='w-8/12'>{product.code}</div>
                </div>
                <div className='flex p-3 items-center '>
                  <div className='w-4/12 text-gray_r-12/70'>Manufacture</div>
                  <div className='w-8/12'>
                    <Link
                      href={createSlug(
                        '/shop/brands/',
                        product.manufacture.name,
                        product.manufacture.id.toString()
                      )}
                    >
                      {product?.manufacture.logo ? (
                        <Image
                          width={100}
                          src={product.manufacture.logo}
                          alt={product.manufacture.name}
                        />
                      ) : (
                        <p className='font-bold text-red-500'>
                          {product.manufacture.name}
                        </p>
                      )}
                    </Link>
                  </div>
                </div>

                <div className='flex p-3 bg-gray_r-4 '>
                  <div className='w-4/12 text-gray_r-12/70'>Berat Barang</div>
                  <div className='w-8/12'>
                    {product?.weight > 0 && <span>{product?.weight} KG</span>}
                    {product?.weight == 0 && (
                      <a
                        href={whatsappUrl('productWeight', {
                          name: product.name,
                          url: createSlug(
                            '/shop/product/',
                            product.name,
                            product.id,
                            true
                          ),
                        })}
                        className='text-danger-500 font-medium'
                      >
                        Tanya Berat
                      </a>
                    )}
                  </div>
                </div>
                <div className='flex p-3 items-center '>
                  <div className='w-4/12 text-gray_r-12/70'>Terjual</div>
                  <div className='w-8/12'>-</div>
                </div>

                <div className='flex p-3 items-center bg-gray_r-4 '>
                  <div className='w-4/12 text-gray_r-12/70'>
                    Persiapan Barang
                  </div>
                  <div className='w-8/12'>
                    {!product?.sla && <Skeleton width='20%' height='16px' />}
                    {product?.sla && (
                      <Tooltip
                        placement='top'
                        label={`Masa Persiapan Barang ${product?.sla?.slaDate}`}
                      >
                        <Box className='w-fit flex items-center gap-x-2'>
                          {product?.sla?.slaDate}
                          <Info size={16} />
                        </Box>
                      </Tooltip>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <div className='p-4 md:p-6 w-full'>
              <ProductPromoSection product={product} productId={product.id} />

              <div className='p-4 md:p-6 md:bg-gray-50 rounded-xl'>
                <h2 className='text-h-md md:text-h-lg font-medium'>
                  Informasi Produk
                </h2>
                <div className='h-4' />
                <div
                  className='leading-relaxed text-gray-700'
                  dangerouslySetInnerHTML={{
                    __html:
                      !product.parent.description ||
                      product.parent.description == '<p><br></p>'
                        ? 'Belum ada deskripsi'
                        : product.parent.description,
                  }}
                />
              </div>
            </div>
          </div>
          <div className='w-[33%]'>
            {product?.isFlashsale > 0 &&
            product?.price?.discountPercentage > 0 ? (
              <>
                <div className='flex gap-x-1 items-center mt-2'>
                  <div className='badge-solid-red text-caption-1'>
                    {product?.price?.discountPercentage}%
                  </div>
                  <div className='text-gray_r-9 line-through text-caption-1'>
                    {currencyFormat(product?.price?.price)}
                  </div>
                  <div className='text-danger-500 font-semibold text-xl'>
                    {currencyFormat(product?.price?.priceDiscount)}
                  </div>
                </div>
                <div className='text-gray_r-9 text-base font-normal mt-1'>
                  Termasuk PPN:{' '}
                  {currencyFormat(
                    product?.price?.priceDiscount * process.env.NEXT_PUBLIC_PPN
                  )}
                </div>
              </>
            ) : (
              <h3 className='text-danger-500 font-semibold mt-1 text-title-md'>
                {product?.price?.price > 0 ? (
                  <>
                    {currencyFormat(product?.price?.price)}
                    <div className='text-gray_r-9 text-base font-normal mt-1'>
                      Termasuk PPN:{' '}
                      {currencyFormat(
                        product?.price?.price * process.env.NEXT_PUBLIC_PPN
                      )}
                    </div>
                  </>
                ) : (
                  <span className='text-gray_r-12/90 font-normal text-h-sm'>
                    Hubungi kami untuk dapatkan harga terbaik,&nbsp;
                    <a
                      href={whatsappUrl('product', {
                        name: product.name,
                        manufacture: product.manufacture?.name,
                        url: createSlug(
                          '/shop/product/',
                          product.name,
                          product.id,
                          true
                        ),
                      })}
                      className='text-danger-500 underline'
                      rel='noopener noreferrer'
                      target='_blank'
                    >
                      klik disini
                    </a>
                  </span>
                )}
              </h3>
            )}
            <div className='flex gap-x-5 items-center py-5'>
              <div className='relative flex items-center'>
                <button
                  type='button'
                  className='absolute left-0 px-2 py-1 h-full text-gray-500'
                  onClick={() => {
                    const n = parseInt(String(quantityInput), 10);
                    const next = Number.isFinite(n) ? Math.max(1, n - 1) : 1;
                    setQuantityInput(next);
                  }}
                >
                  -
                </button>

                <input
                  type='number'
                  id='quantity'
                  min={1}
                  step={1}
                  inputMode='numeric'
                  pattern='[0-9]*'
                  value={quantityInput}
                  onChange={(e) => {
                    const raw = e.target.value.trim();
                    const n = parseInt(raw, 10);
                    setQuantityInput(Number.isFinite(n) && n > 0 ? n : 1);
                  }}
                  onKeyDown={(e) => {
                    if (['e', 'E', '+', '-', '.'].includes(e.key))
                      e.preventDefault();
                  }}
                  className='w-24 h-10 text-center border border-gray-300 rounded focus:outline-none'
                />

                <button
                  type='button'
                  className='absolute right-0 px-2 py-1 h-full text-gray-500'
                  onClick={() => {
                    const n = parseInt(String(quantityInput), 10);
                    const next = (Number.isFinite(n) ? n : 0) + 1;
                    setQuantityInput(next);
                  }}
                >
                  +
                </button>
              </div>

              <div>
                <Skeleton
                  isLoaded={!isLoadingSLA}
                  h='21px'
                  // w={16}
                  className={
                    product?.sla?.qty < 10 ? 'text-red-600 font-medium' : ''
                  }
                >
                  Stock : {product?.sla?.qty}{' '}
                </Skeleton>
              </div>
              <div>
                {qtyPickUp > 0 && (
                  <Link href='/panduan-pick-up-service' className='group'>
                    <Image
                      src='/images/PICKUP-NOW.png'
                      className='group-hover:scale-105 transition-transform duration-200 w-28'
                      alt='pickup now'
                    />
                  </Link>
                )}
              </div>
            </div>
            {qtyPickUp > 0 && (
              <>
                <div className='text-[12px] mt-1 text-red-500 italic'>
                  * {qtyPickUp} barang bisa di pickup
                </div>
                <div className='h-4' />
              </>
            )}
            <div className='flex gap-x-3'>
              <Button
                onClick={() => handleAddToCart(product.id)}
                className='w-full'
                colorScheme='red'
                variant={'outline'}
              >
                Keranjang
              </Button>
              <Button
                onClick={() => handleBuy(product.id)}
                className='w-full'
                colorScheme='red'
              >
                Beli
              </Button>
            </div>
            <Button
              onClick={() => handleButton(product.id)}
              color={'red'}
              colorScheme='white'
              className='w-full border-2 p-2 gap-1 mt-2 hover:bg-slate-100 flex items-center'
            >
              <ImageNext
                src='/images/doc_red.svg'
                alt='penawaran instan'
                className=''
                width={25}
                height={25}
              />
              Penawaran Harga Instan
            </Button>
            <div className='flex py-5'>
              <div className='flex gap-x-5 items-center justify-center'>
                <Button
                  as={Link}
                  href={createdAskUrl}
                  variant='link'
                  target='_blank'
                  colorScheme='gray'
                  leftIcon={<MessageCircleIcon size={18} />}
                >
                  Ask Admin
                </Button>

                <span>|</span>

                <button
                  className='flex items-center gap-x-1'
                  onClick={toggleWishlist}
                >
                  {wishlist.data?.productTotal > 0 ? (
                    <HeartIcon className='w-6 fill-danger-500 text-danger-500' />
                  ) : (
                    <HeartIcon className='w-6' />
                  )}
                  Wishlist
                </button>

                <span>|</span>

                <RWebShare
                  data={{
                    text: 'Check out this product',
                    title: `${product.name} - Indoteknik.com`,
                    url: SELF_HOST + router.asPath,
                  }}
                >
                  <Button
                    variant='link'
                    colorScheme='gray'
                    leftIcon={<Share2Icon size={18} />}
                  >
                    Share
                  </Button>
                </RWebShare>
              </div>
            </div>
            <div className='border border-gray_r-6 overflow-auto mt-4'>
              <div className='font-medium text-center p-4 bg-gray_r-1 border-b border-gray_r-6 sticky top-0 z-10'>
                Produk Serupa
              </div>
              <div className='h-full divide-y divide-gray_r-6 max-h-[500px]'>
                {productSimilarInBrand &&
                  productSimilarInBrand?.map((product) => (
                    <div className='py-2' key={product.id}>
                      <ProductCard product={product} variant='horizontal' />
                    </div>
                  ))}
              </div>
            </div>
          </div>
        </div>

        <div className='my-12'>
          <div className='text-h-lg font-semibold mb-6'>
            Kamu Mungkin Juga Suka
          </div>
          <LazyLoad>
            <SimilarBottom product={product} />
          </LazyLoad>
          {/* <LazyLoad>
            <ProductSimilar query={productSimilarQuery} />
          </LazyLoad> */}
        </div>

        <BottomPopup
          className='!container'
          title='Berhasil Ditambahkan'
          active={addCartAlert}
          close={() => setAddCartAlert(false)}
        >
          <div className='flex mt-4'>
            <div className='w-[10%]'>
              <Image
                src={product.image + '?variant=True'}
                alt={product.name}
                className='h-32 object-contain object-center w-full border border-gray_r-4'
              />
            </div>
            <div className='ml-3 flex flex-1 items-center font-normal'>
              {product.name}
            </div>
            <div className='ml-3 flex items-center font-normal'>
              <Link
                href='/shop/cart'
                className='flex-1 py-2 text-gray_r-12 btn-yellow'
              >
                Lihat Keranjang
              </Link>
            </div>
          </div>

          <div className='mt-8 mb-4'>
            <div className='text-h-sm font-semibold mb-6'>
              Kamu Mungkin Juga Suka
            </div>
            <LazyLoad>
              <SimilarBottom product={product} />
            </LazyLoad>
            {/* <LazyLoad>
              <ProductSimilar query={productSimilarQuery} />
            </LazyLoad> */}
          </div>
        </BottomPopup>
      </div>
    </DesktopView>
  );
};

const informationTabOptions = [
  { value: 'description', label: 'Deskripsi' },
  { value: 'information', label: 'Info Penting' },
];

const TabButton = ({ children, active, ...props }) => {
  const activeClassName = active
    ? 'text-danger-500 underline underline-offset-4'
    : 'text-gray_r-12/80';
  return (
    <button
      {...props}
      type='button'
      className={`font-medium ${activeClassName}`}
    >
      {children}
    </button>
  );
};

const TabContent = ({ children, active, className = '', ...props }) => (
  <div {...props} className={`${active ? 'block' : 'hidden'} ${className}`}>
    {children}
  </div>
);

export default ProductDesktopVariant;
