import React, { useState } from "react"
import { SelectProps } from "antd"
import { SelectMarketCategoryComponent } from "@component/Common/SelectMarketCate"
import { useGetMarketCategories } from "@/hook/useMarket"
import { IMarketCategory, IMarketCategoryQuery } from "@/type/Market"
import { debounce } from "lodash"

export interface SelectMarketCategoryProps extends Omit<SelectProps, "options"> {
  options?: IMarketCategory[]
  refetchOnMount?: boolean
  onChange?: any
  params?: IMarketCategoryQuery
}

export const SelectMarketCategory = (props: SelectMarketCategoryProps) => {
  const [keyword, setKeyword] = useState("")
  const { data: marketCategories, isLoading } = useGetMarketCategories(keyword.trim()?.length >= 3 ? { search: keyword.trim() } : {}, {
    refetchOnMount: props?.refetchOnMount,
  })

  const onSearch = (value: any) => {
    if (value.trim().length >= 3) {
      setKeyword(value.trim())
    } else {
      setKeyword("")
    }
  }

  console.log("marketCategories", marketCategories)

  return (
    <SelectMarketCategoryComponent
      loading={isLoading}
      options={marketCategories?.data?.data?.categories}
      onSearch={debounce((e) => onSearch(e), 500)}
      onBlur={() => onSearch("")}
      onClear={() => onSearch("")}
      {...props}
    />
  )
}
