// @ts-nocheck
"use client"
import { useCartStore } from "@/app/store/cartStore"
import { selectStyle } from "@/lib/utils"
import { Product } from "@/modules/products/product"
import { useAuth } from "@/providers/AuthProvider"
import { useQueryClient } from "@tanstack/react-query"
import Select from "react-select"
import { useState, useTransition } from "react"
// import debounce from "lodash.debounce"

type Props = {
  product: Product
  inSingleProduct?: boolean
}
const SingleProductCounter = ({ product, inSingleProduct = false }: Props) => {
  const user = useAuth()
  const { updateProductCount, getProducts, getPriceSummary, gettingDataState } = useCartStore()
  const queryClient = useQueryClient()
  const [countLoading, setCountLoading] = useState(false)

  const options = Array.from({ length: product?.product?.count }, (_, i) => ({
    label: i + 1,
    value: i + 1,
  }))

  const handelCounter = (value: number) => {
    if (inSingleProduct) {
      setCountLoading(true)
      updateProductCount({ product_id: product?.product?.id, count: value })
        .then(() => {
          // Refetch the specific query with the key ["products", product.id]
          // queryClient.refetchQueries(["products", product?.id])
          // or
          queryClient.invalidateQueries(["products", product?.product?.id])
        })
        .finally(() => setCountLoading(false))
      // .then(async () => await getPriceSummary())
      // refetch() => "products", id
      // here i want to refetch  query that has key ["products", id]
    } else {
      updateProductCount({ product_id: product?.product?.id, count: value })
        .then(async () => await getPriceSummary())
        .then(async () => await getProducts())
    }
  }

  // if (!user?.token || !product?.is_cart) return null
  if (!user?.token) return null

  console.log("product?.count_of_cart", product)
  return (
    <div className="flex items-center">
      <Select
        className="basic-single hide_scroll min-w-[60px]"
        classNamePrefix="select"
        isLoading={gettingDataState || countLoading}
        isDisabled={gettingDataState || countLoading}
        isSearchable
        options={options}
        value={{
          label: product?.count,
          value: product?.count,
        }}
        onChange={(option) => {
          // setValue(option as never)
          // @ts-ignore
          handelCounter(option!.value)
        }}
        styles={selectStyle}
      />
    </div>
  )
}

export default SingleProductCounter
