import clsx from 'clsx';
import ImageNext from 'next/image';
import { useRouter } from 'next/router';
import { useMemo, useEffect, useState } from 'react';

import Image from '@/core/components/elements/Image/Image';
import Link from '@/core/components/elements/Link/Link';
import currencyFormat from '@/core/utils/currencyFormat';
import { sellingProductFormat } from '@/core/utils/formatValue';
import { createSlug } from '@/core/utils/slug';
import whatsappUrl from '@/core/utils/whatsappUrl';
import useUtmSource from '~/hooks/useUtmSource';

const ProductCard = ({ product, simpleTitle, variant = 'vertical' }) => {
  const router = useRouter();
  const utmSource = useUtmSource();

  const [isSni, setIsSni] = useState(false);
  const [isTkdn, setTkdn] = useState(false);

  useEffect(() => {
    // Lakukan pemanggilan API untuk memeriksa isSni
    const fetchSniData = async () => {
      try {
        const response = await fetch('URL_API_SNI');
        const data = await response.json();
        if (data && data.sni) {
          setIsSni(true);
        } else {
          setIsSni(false);
        }
      } catch (error) {
        console.error('Error fetching SNI data:', error);
        setIsSni(false);
      }
    };

    // Lakukan pemanggilan API untuk memeriksa isTkdn
    const fetchTkdnData = async () => {
      try {
        const response = await fetch('URL_API_TKDN');
        const data = await response.json();
        if (data && data.tkdn) {
          setTkdn(true);
        } else {
          setTkdn(false);
        }
      } catch (error) {
        console.error('Error fetching TKDN data:', error);
        setTkdn(false);
      }
    };
    fetchSniData();
    fetchTkdnData();
    return () => {
    };
  }, []);

  const callForPriceWhatsapp = whatsappUrl('product', {
    name: product.name,
    manufacture: product.manufacture?.name,
    url: createSlug('/shop/product/', product.name, product.id, true),
  });

  const image = useMemo(() => {
    if (product.image) return product.image + '?ratio=square';
    return '/images/noimage.jpeg';
  }, [product.image]);

  const URL = {
    product:
      createSlug('/shop/product/', product?.name, product?.id) +
      `?utm_source=${utmSource}`,
    manufacture: createSlug(
      '/shop/brands/',
      product?.manufacture?.name,
      product?.manufacture.id
    ),
  };

  if (variant == 'vertical') {
    return (
      <div className='rounded shadow-sm border border-gray_r-4 bg-white h-[300px] md:h-[350px]'>
        <Link href={URL.product} className='border-b border-gray_r-4 relative'>
        <div className="relative">
          <Image
            src={image}
            alt={product?.name}
            className="gambarA w-full object-contain object-center h-36 sm:h-48"
          />
          <div className="absolute top-0 right-0 flex  mt-3">
            <div className="gambarB ">
              {isSni && (
                <ImageNext
                  src="/images/sni-logo.png"
                  alt="SNI Logo"
                  className="w-4 h-5 object-contain object-top   sm:h-6"
                  width={50}
                  height={50}
                />
              )}
            </div>
            <div className="gambarC  ">
              {isTkdn && (
                <ImageNext
                  src="/images/TKDN.png"
                  alt="TKDN"
                  className="w-11 h-6 object-contain object-top  ml-1 mr-1 sm:h-6"
                  width={50}
                  height={50}
                />
              )}
            </div>
          </div>
        </div>


          {router.pathname != '/' && product?.flashSale?.id > 0 && (
            <div className='absolute bottom-0 w-full grid'>
              <div className='absolute bottom-0 w-full h-full'>
                <ImageNext
                  src='/images/BG-FLASH-SALE.jpg'
                  className='h-full'
                  width={1000}
                  height={100}
                />
              </div>
              <div className='relative'>
                <div className='flex gap-x-1 items-center p-2 justify-center'>
                  <div className='bg-yellow-400 rounded-lg p-1 h-6 w-19 flex items-center justify-center '>
                    <span className='text-sm font-bold text-black'>
                      {Math.floor(product?.lowestPrice.discountPercentage)}%
                    </span>
                  </div>
                  <div className='bg-red-600 border border-solid border-yellow-400 p-2 rounded-full h-6 flex w-fit items-center justify-center gap-x-2'>
                    <ImageNext
                      src='/images/ICON_FLASH_SALE_WEBSITE_INDOTEKNIK.svg'
                      width={13}
                      height={5}
                    />
                    <span className='text-white text-[9px] md:text-[10px] font-semibold'>
                      {product?.flashSale?.tag != 'false' ||
                      product?.flashSale?.tag
                        ? product?.flashSale?.tag
                        : 'FLASH SALE'}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          )}
          {product.variantTotal > 1 && (
            <div className='absolute badge-gray bottom-1.5 left-1.5'>
              {product.variantTotal} Varian
            </div>
          )}
        </Link>
        <div className='p-2 sm:p-3 pb-3 text-caption-2 sm:text-body-2 leading-5'>
          {product?.manufacture?.name ? (
            <Link href={URL.manufacture} className='mb-1'>
              {product.manufacture.name}
            </Link>
          ) : (
            <div>-</div>
          )}
          <Link
            href={URL.product}
            className={`mb-2 !text-gray_r-12 leading-6 block line-clamp-3 h-[64px]`}
            title={product?.name}
          >
            {product?.name}
          </Link>
          {product?.flashSale?.id > 0 &&
          product?.lowestPrice.discountPercentage > 0 ? (
            <>
              <div className='flex gap-x-1 mb-1 items-center'>
                <div className='text-gray_r-11 line-through text-[11px] sm:text-caption-2'>
                  {currencyFormat(product.lowestPrice.price)}
                </div>
                <div className='badge-solid-red'>
                  {Math.floor(product?.lowestPrice.discountPercentage)}%
                </div>
              </div>
              <div className='text-danger-500 font-semibold mb-2'>
                {product?.lowestPrice.priceDiscount > 0 ? (
                  currencyFormat(product?.lowestPrice.priceDiscount)
                ) : (
                  <a
                    rel='noopener noreferrer'
                    target='_blank'
                    href={callForPriceWhatsapp}
                  >
                    Call for Inquiry
                  </a>
                )}
              </div>
            </>
          ) : (
            <div className='text-danger-500 font-semibold mb-2 min-h-[40px]'>
              {product?.lowestPrice.price > 0 ? (
                <>
                  {currencyFormat(product?.lowestPrice.price)}
                  <div className='text-gray_r-9 text-[10px] font-normal mt-2'>
                    Inc. PPN:{' '}
                    {currencyFormat(
                      product.lowestPrice.price * process.env.NEXT_PUBLIC_PPN
                    )}
                  </div>
                </>
              ) : (
                <a
                  rel='noopener noreferrer'
                  target='_blank'
                  href={callForPriceWhatsapp}
                >
                  Call for Inquiry
                </a>
              )}
            </div>
          )}

          <div className='flex w-full items-center gap-x-1 '>
            {product?.stockTotal > 0 && (
              <div className='badge-solid-red'>Ready Stock</div>
            )}
            {/* <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> */}
            {product?.qtySold > 0 && (
              <div className='text-gray_r-9 text-[11px]'>
                {sellingProductFormat(product?.qtySold) + ' Terjual'}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  if (variant == 'horizontal') {
    return (
      <div className='flex bg-white'>
        <div className='w-4/12'>
          <Link href={URL.product} className='relative'>
          <div className="relative">
          <Image
            src={image}
            alt={product?.name}
            className="gambarA w-full object-contain object-center h-36 sm:h-48"
          />
          <div className="absolute top-0 right-0 flex  mt-3">
            <div className="gambarB ">
              {!isSni && (
                <ImageNext
                  src="/images/sni-logo.png"
                  alt="SNI Logo"
                  className="w-4 h-5 object-contain object-top   sm:h-6"
                  width={50}
                  height={50}
                />
              )}
            </div>
            <div className="gambarC  ">
              {!isTkdn && (
                <ImageNext
                  src="/images/TKDN.png"
                  alt="TKDN"
                  className="w-11 h-6 object-contain object-top  ml-1 sm:h-6"
                  width={50}
                  height={50}
                />
              )}
            </div>
          </div>
        </div>
            {product.variantTotal > 1 && (
              <div className='absolute badge-gray bottom-1.5 left-1.5'>
                {product.variantTotal} Varian
              </div>
            )}
          </Link>
        </div>
        <div className='w-8/12 p-2'>
          {product.flashSale.id > 0 && (
            <div className='bg-red-600 rounded-full mb-1 p-2 pl-3 pr-3 flex w-fit items-center gap-x-1'>
              <ImageNext
                src='/images/ICON_FLASH_SALE_WEBSITE_INDOTEKNIK.svg'
                width={15}
                height={10}
              />
              <span className='text-white text-xs font-semibold'>
                {' '}
                {product?.flashSale?.tag != 'false' || product?.flashSale?.tag
                  ? product?.flashSale?.tag
                  : 'FLASH SALE'}
              </span>
            </div>
          )}
          {product?.manufacture?.name ? (
            <Link href={URL.manufacture} className='mb-1'>
              {product.manufacture.name}
            </Link>
          ) : (
            <div>-</div>
          )}
          <Link
            href={URL.product}
            className={`mb-3 !text-gray_r-12 leading-6 line-clamp-3`}
          >
            {product?.name}
          </Link>
          {product?.flashSale?.id > 0 &&
          product?.lowestPrice?.discountPercentage > 0 ? (
            <>
              {product?.lowestPrice.discountPercentage > 0 && (
                <div className='flex gap-x-1 mb-1 items-center'>
                  <div className='badge-solid-red'>
                    {Math.floor(product?.lowestPrice?.discountPercentage)}%
                  </div>
                  <div className='text-gray_r-11 line-through text-caption-2'>
                    {currencyFormat(product?.lowestPrice?.price)}
                  </div>
                </div>
              )}

              <div className='text-danger-500 font-semibold mb-2'>
                {product?.lowestPrice?.priceDiscount > 0 ? (
                  currencyFormat(product?.lowestPrice?.priceDiscount)
                ) : (
                  <a
                    rel='noopener noreferrer'
                    target='_blank'
                    href={callForPriceWhatsapp}
                  >
                    Call for Inquiry
                  </a>
                )}
              </div>
            </>
          ) : (
            <div className='text-danger-500 font-semibold mb-2 min-h-[40px]'>
              {product?.lowestPrice.price > 0 ? (
                <>
                  {currencyFormat(product?.lowestPrice.price)}
                  <div className='text-gray_r-9 text-[11px] sm:text-caption-2 font-normal mt-2'>
                    Inc. PPN:{' '}
                    {currencyFormat(
                      product.lowestPrice.price * process.env.NEXT_PUBLIC_PPN
                    )}
                  </div>
                </>
              ) : (
                <a
                  rel='noopener noreferrer'
                  target='_blank'
                  href={callForPriceWhatsapp}
                >
                  Call for Inquiry
                </a>
              )}
            </div>
          )}

          <div className='flex w-full items-center gap-x-1 '>
            {product?.stockTotal > 0 && (
              <div className='badge-solid-red'>Ready Stock</div>
            )}
            {/* <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> */}
            {product?.qtySold > 0 && (
              <div className='text-gray_r-9 text-[11px]'>
                {sellingProductFormat(product?.qtySold) + ' Terjual'}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }
};

export default ProductCard;
