import Divider from '@/core/components/elements/Divider/Divider'
import Image from '@/core/components/elements/Image/Image'
import Link from '@/core/components/elements/Link/Link'
import currencyFormat from '@/core/utils/currencyFormat'
import { useEffect, useState } from 'react'
import Select from 'react-select'
import ProductSimilar from '../ProductSimilar'
import LazyLoad from 'react-lazy-load'
import { updateItemCart } from '@/core/utils/cart'
import { HeartIcon } from '@heroicons/react/24/outline'
import { useRouter } from 'next/router'
import MobileView from '@/core/components/views/MobileView'
import { toast } from 'react-hot-toast'
import { createSlug } from '@/core/utils/slug'
import BottomPopup from '@/core/components/elements/Popup/BottomPopup'
import whatsappUrl from '@/core/utils/whatsappUrl'
import PromotionType from '@/lib/promotinProgram/components/PromotionType'

const ProductMobile = ({ product, wishlist, toggleWishlist }) => {
  const router = useRouter()

  const [quantity, setQuantity] = useState('1')
  const [selectedVariant, setSelectedVariant] = useState(null)
  const [informationTab, setInformationTab] = useState(informationTabOptions[0].value)
  const [addCartAlert, setAddCartAlert] = useState(false)

  const getLowestPrice = () => {
    const prices = product.variants.map((variant) => variant.price)
    const lowest = prices.reduce((lowest, price) => {
      return price.priceDiscount < lowest.priceDiscount ? price : lowest
    }, prices[0])
    return lowest
  }

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

  const variantOptions = product.variants?.map((variant) => ({
    value: variant.id,
    label:
      (variant.code ? `[${variant.code}] ` : '') +
      (variant.attributes.length > 0 ? variant.attributes.join(', ') : product.name)
  }))

  useEffect(() => {
    if (!selectedVariant && variantOptions.length == 1) {
      setSelectedVariant(variantOptions[0])
    }
  }, [selectedVariant, variantOptions])

  useEffect(() => {
    if (selectedVariant) {
      const variant = product.variants.find((variant) => variant.id == selectedVariant.value)
      const variantAttributes =
        variant.attributes.length > 0 ? ' - ' + variant.attributes.join(', ') : ''

      setActiveVariant({
        id: variant.id,
        code: variant.code,
        name: variant.parent.name + variantAttributes,
        price: variant.price,
        stock: variant.stock,
        weight: variant.weight
      })
    }
  }, [selectedVariant, product])

  const validAction = () => {
    let isValid = true
    if (!selectedVariant) {
      toast.error('Pilih varian terlebih dahulu')
      isValid = false
    }
    if (!quantity || quantity < 1 || isNaN(parseInt(quantity))) {
      toast.error('Jumlah barang minimal 1')
      isValid = false
    }
    return isValid
  }

  const handleClickCart = () => {
    if (!validAction()) return
    updateItemCart({
      productId: activeVariant.id,
      quantity,
      selected: true
    })
    setAddCartAlert(true)
  }

  const handleClickBuy = () => {
    if (!validAction()) return
    router.push(`/shop/checkout?productId=${activeVariant.id}&quantity=${quantity}`)
  }

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

  return (
    <MobileView>
      <Image
        src={product.image}
        alt={product.name}
        className='h-72 object-contain object-center w-full border-b border-gray_r-4'
      />

      <div className='p-4'>
        <div className='flex items-end mb-2'>
          {product.manufacture?.name ? (
            <Link
              href={createSlug('/shop/brands/', product.manufacture?.name, product.manufacture?.id)}
            >
              {product.manufacture?.name}
            </Link>
          ) : (
            <div>-</div>
          )}
          <button type='button' className='ml-auto' onClick={toggleWishlist}>
            {wishlist.data?.productTotal > 0 ? (
              <HeartIcon className='w-6 fill-danger-500 text-danger-500' />
            ) : (
              <HeartIcon className='w-6' />
            )}
          </button>
        </div>
        <h1 className='leading-6 font-medium mb-3'>{activeVariant?.name}</h1>

        {product.variants.length > 1 &&
          activeVariant.price.priceDiscount > 0 &&
          !selectedVariant && (
            <div className='text-gray_r-12/80 text-caption-2 mt-2 mb-1'>Harga mulai dari: </div>
          )}

        {activeVariant?.price?.discountPercentage > 0 && (
          <div className='flex gap-x-1 items-center'>
            <div className='text-gray_r-11 line-through text-caption-1'>
              {currencyFormat(activeVariant?.price?.price)}
            </div>
            <div className='badge-solid-red'>{activeVariant?.price?.discountPercentage}%</div>
          </div>
        )}
        <h3 className='text-danger-500 font-semibold mt-1'>
          {activeVariant?.price?.priceDiscount > 0 ? (
            currencyFormat(activeVariant?.price?.priceDiscount)
          ) : (
            <span className='text-gray_r-11 leading-6 font-normal'>
              Hubungi kami untuk dapatkan harga terbaik,&nbsp;
              <a
                href={whatsappUrl('product', {
                  name: product.name,
                  url: createSlug('/shop/product/', product.name, product.id, true)
                })}
                className='text-danger-500 underline'
              >
                klik disini
              </a>
            </span>
          )}
        </h3>
      </div>

      <Divider />

      <div className='p-4'>
        <div className='mb-5'>
          {/* <PromotionType></PromotionType> */}
          <button type='button' className='text-gray-900  flex p-3 rounded-lg bg-white border border-gray-300  hover:bg-gray-100 py-2.5 w-[100%]'>
           <span className='text-left'>%</span>
           <span className='text-left ml-5'>Makin Hemat Pakai Promo</span>
          </button>
        </div>
        <div>
          <label className='flex justify-between'>
            Pilih Varian:
            <span className='text-gray_r-11'>{product?.variantTotal} Varian</span>
          </label>
          <Select
            name='variant'
            classNamePrefix='form-select'
            options={variantOptions}
            className='mt-2'
            value={selectedVariant}
            onChange={(option) => setSelectedVariant(option)}
            isSearchable={product.variantTotal > 10}
          />
        </div>
        <div className='mt-4 mb-2'>Jumlah</div>
        <div className='flex gap-x-3'>
          <div className='w-2/12'>
            <input
              name='quantity'
              type='number'
              className='form-input'
              value={quantity}
              onChange={(e) => setQuantity(e.target.value)}
            />
          </div>
          <button type='button' className='btn-yellow flex-1' onClick={handleClickCart}>
            Keranjang
          </button>
          <button type='button' className='btn-solid-red flex-1' onClick={handleClickBuy}>
            Beli
          </button>
        </div>
      </div>

      <Divider />

      <div className='p-4'>
        <h2 className='font-semibold'>Informasi Produk</h2>
        <div className='flex gap-x-4 mt-4 mb-3'>
          {informationTabOptions.map((option) => (
            <TabButton
              value={option.value}
              key={option.value}
              active={informationTab == option.value}
              onClick={() => setInformationTab(option.value)}
            >
              {option.label}
            </TabButton>
          ))}
        </div>

        <TabContent
          active={informationTab == 'specification'}
          className='rounded border border-gray_r-6 divide-y divide-gray_r-6'
        >
          <SpecificationContent label='Jumlah Varian'>
            <span>{product?.variantTotal} Varian</span>
          </SpecificationContent>
          <SpecificationContent label='Nomor SKU'>
            <span>SKU-{product?.id}</span>
          </SpecificationContent>
          <SpecificationContent label='Part Number'>
            <span>{activeVariant?.code || '-'}</span>
          </SpecificationContent>
          <SpecificationContent label='Stok'>
            {activeVariant?.stock > 0 && (
              <span className='flex gap-x-1.5'>
                <div className='badge-solid-red'>Ready Stock</div>
                <div className='badge-gray'>{activeVariant?.stock > 5 ? '> 5' : '< 5'}</div>
              </span>
            )}
            {activeVariant?.stock == 0 && (
              <a
                href={whatsappUrl('product', {
                  name: product.name,
                  url: createSlug('/shop/product/', product.name, product.id, true)
                })}
                className='text-danger-500 font-medium'
              >
                Tanya Stok
              </a>
            )}
          </SpecificationContent>
          <SpecificationContent label='Berat Barang'>
            {activeVariant?.weight > 0 && <span>{activeVariant?.weight} KG</span>}
            {activeVariant?.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>
            )}
          </SpecificationContent>
        </TabContent>

        <TabContent
          active={informationTab == 'description'}
          className='leading-6 text-gray_r-11'
          dangerouslySetInnerHTML={{
            __html: product.description != '' ? product.description : 'Belum ada deskripsi produk.'
          }}
        />
      </div>

      <Divider />

      <div className='p-4'>
        <h2 className='font-semibold mb-4'>Kamu Mungkin Juga Suka</h2>
        <LazyLoad>
          <ProductSimilar query={productSimilarQuery} />
        </LazyLoad>
      </div>

      <BottomPopup
        title='Berhasil Ditambahkan'
        active={addCartAlert}
        close={() => setAddCartAlert(false)}
      >
        <div className='flex mt-4'>
          <div className='w-[15%]'>
            <Image
              src={product.image}
              alt={product.name}
              className='h-20 object-contain object-center w-full border border-gray_r-4'
            />
          </div>
          <div className='ml-3 flex flex-1 items-center text-sm font-normal'>{product.name}</div>
          <div className='ml-3 flex items-center text-sm 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>
            <ProductSimilar query={productSimilarQuery} />
          </LazyLoad>
        </div>
      </BottomPopup>
    </MobileView>
  )
}

const informationTabOptions = [
  { value: 'specification', label: 'Spesifikasi' },
  { 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-11'
  return (
    <button {...props} type='button' className={`font-medium pb-1 ${activeClassName}`}>
      {children}
    </button>
  )
}

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

const SpecificationContent = ({ children, label }) => (
  <div className='flex justify-between p-3'>
    <span className='text-gray_r-11'>{label}</span>
    {children}
  </div>
)

export default ProductMobile
