import style from '../styles/price-action.module.css';

import React, { useEffect } from 'react';
import formatCurrency from '~/libs/formatCurrency';
import { IProductDetail } from '~/types/product';
import { useProductDetail } from '../stores/useProductDetail';
import AddToCart from './AddToCart';
import Link from 'next/link';
import { getAuth } from '~/libs/auth';

type Props = {
  product: IProductDetail;
};

const PriceAction = ({ product }: Props) => {
  const {
    activePrice,
    setActive,
    activeVariantId,
    quantityInput,
    setQuantityInput,
    askAdminUrl,
    isApproval,
    setIsApproval,
    selectedVariant,
    sla,
  } = useProductDetail();

  useEffect(() => {
    setActive(selectedVariant);
    if (product.variants.length > 2 && product.variants[0].price.price === 0) {
      const variants = product.variants;
      for (let i = 0; i < variants.length; i++) {
        if (variants[i].price.price > 0) {
          setActive(variants[i]);
          break;
        }
      }
    }
  }, [product, setActive, selectedVariant]);

  let voucherPastiHemat = 0;

  if (
    product?.voucher_pasti_hemat
      ? product?.voucher_pasti_hemat.length
      : voucherPastiHemat > 0
  ) {
    const stringVoucher = product?.voucher_pasti_hemat[0];
    const validJsonString = stringVoucher.replace(/'/g, '"');
    voucherPastiHemat = JSON.parse(validJsonString);
  }

  return (
    <div
      className='block md:sticky top-[150px] bg-white py-0 md:py-6 z-10'
      id='price-section'
    >
      {!!activePrice && activePrice.price > 0 && (
        <>
          <div className='flex items-end gap-x-2'>
            {activePrice.discount_percentage > 0 && (
              <>
                <div className={style['disc-badge']}>
                  {Math.floor(activePrice.discount_percentage)}%
                </div>
                <div className={style['disc-price']}>
                  Rp {formatCurrency(activePrice.price || 0)}
                </div>
              </>
            )}
            <div className={style['main-price']}>
              Rp {formatCurrency(activePrice.price_discount || 0)}
            </div>
          </div>
          <div className='h-1' />
          <div className={style['secondary-text']}>
            Termasuk PPN: Rp{' '}
            {formatCurrency(Math.round(activePrice.price_discount * 1.11))}
          </div>
        </>
      )}

      {!!activePrice && activePrice.price === 0 && (
        <span>
          Hubungi kami untuk dapatkan harga terbaik,{' '}
          <Link
            href={askAdminUrl}
            target='_blank'
            className={style['contact-us']}
          >
            klik disini
          </Link>
        </span>
      )}

      <div className='h-4' />
      <div className='flex gap-x-5 items-center'>
        <div>
          <label htmlFor='quantity' className='hidden'>
            Quantity
          </label>
          <div className='flex items-center space-x-2'>
            <input
              type='number'
              id='quantity'
              value={quantityInput}
              onChange={(e) => setQuantityInput(e.target.value)}
              className={style['quantity-input']}
            />
          </div>
        </div>
        <div>
          <span className={sla?.qty < 10 ? 'text-red-600 font-medium' : ''}>
            {' '}
            Stock : {sla?.qty}{' '}
          </span>
        </div>
      </div>
      <div className='h-4' />

      <div className={style['action-wrapper']}>
        <AddToCart
          products={product}
          variantId={activeVariantId}
          quantity={Number(quantityInput)}
        />
        {!isApproval && (
          <AddToCart
            source='buy'
            products={product}
            variantId={activeVariantId}
            quantity={Number(quantityInput)}
          />
        )}
      </div>
    </div>
  );
};

export default PriceAction;
