import style from '../styles/variant-list.module.css'

import React from 'react'
import { Button, Skeleton } from '@chakra-ui/react'

import formatCurrency from '~/libs/formatCurrency'
import clsxm from '~/libs/clsxm'
import { IProductVariantDetail, IProductVariantSLA } from '~/types/productVariant'
import { useProductDetail } from '../stores/useProductDetail'
import { LazyLoadComponent } from 'react-lazy-load-image-component';
import { getVariantSLA } from '~/services/productVariant'
import { useQuery } from 'react-query'

type Props = {
  variants: IProductVariantDetail[]
}

const VariantList = ({ variants }: Props) => {
  return (
    <div className='overflow-auto'>
      <div className={style['wrapper']}>
        <div className={style['header']}>
          <div className="w-2/12 sticky left-0 bg-gray-200">Part Number</div>
          <div className="w-2/12">Variant</div>
          <div className="w-2/12">Stock</div>
          <div className="w-2/12">Masa Persiapan</div>
          <div className="w-1/12">Berat</div>
          <div className="w-2/12">Harga</div>
        </div>
        {variants.map((variant) => (
          <LazyLoadComponent key={variant.id}>
            <Row variant={variant} />
          </LazyLoadComponent>
        ))}
      </div>
    </div>
  )
}

const Row = ({ variant }: { variant: IProductVariantDetail }) => {
  const { activeVariantId, setActive } = useProductDetail()
  const querySLA = useQuery<IProductVariantSLA>({
    queryKey: ['variant-sla', variant.id],
    queryFn: () => getVariantSLA(variant.id),
  })

  const sla = querySLA?.data

  return (
    <div className={style['row']}>
      <div className='w-2/12 sticky left-0 bg-white md:bg-transparent'>{variant.code}</div>
      <div className='w-2/12'>{variant.attributes.join(', ')}</div>
      <div className='w-2/12'>
        <Skeleton isLoaded={querySLA.isSuccess} h='21px' w={16}>
          {sla?.qty !== undefined && (
            <>
              {sla.qty > 0 && sla.qty}
              {sla.qty == 0 && '-'}
            </>
          )}
        </Skeleton>
      </div>
      <div className='w-2/12'>
        <Skeleton isLoaded={querySLA.isSuccess} h='21px' w={16}>
          {sla?.sla_date}
        </Skeleton>
      </div>
      <div className='w-1/12'>
        {variant.weight > 0 ? `${variant.weight} Kg` : '-'}
      </div>
      <div className='w-2/12'>
        {variant.price.price > 0 && `Rp ${formatCurrency(variant.price.price)}`}
        {variant.price.price === 0 && '-'}
      </div>
      <div className='w-1/12'>
        <Button
          onClick={() => setActive(variant)}
          size='sm'
          w='100%'
          className={clsxm(style['select-btn'], {
            [style['select-btn--active']]: variant.id === activeVariantId
          })}
        >
          Pilih
        </Button>
      </div>
    </div>
  )
}

export default VariantList