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'

type Props = {
  product: IProductDetail
}

const PriceAction = ({ product }: Props) => {
  const {
    activePrice,
    setActive,
    activeVariantId,
    quantityInput,
    setQuantityInput,
    askAdminUrl
  } = useProductDetail()

  useEffect(() => {
    setActive(product.variants[0])
  }, [product, setActive]);

  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={style['action-wrapper']}>
        <label htmlFor="quantity" className='hidden'>Quantity</label>
        <input type='number' id='quantity' value={quantityInput} onChange={(e) => setQuantityInput(e.target.value)} className={style['quantity-input']} />
        <AddToCart variantId={activeVariantId} quantity={Number(quantityInput)} />
        <AddToCart source='buy' variantId={activeVariantId} quantity={Number(quantityInput)} />
      </div>
    </div>
  )
}

export default PriceAction