import React, { useState } from 'react';
import { Select, Spin } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { LuSearch } from 'react-icons/lu';
import { useGetBaseProduct } from '../../../api/baseProduct';
import { Product } from '../../../types/item';

const SearchButton: React.FC = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const [query, setQuery] = useState<string | null>(searchParams.get('search'));

  const { data, isLoading } = useGetBaseProduct({
    name: query,
  });
  const BaseProducts = (data?.products as Product[]) || [];

  const options = BaseProducts.map((product: any) => ({
    value: product.base_product_id,
    label: product?.name as string, // Ensuring the label is a string
  }));

  const handleSearchChange = (value: string) => {
    setQuery(value);
    navigate(`${window.location.pathname}?search=${value}`, {
      replace: true,
    });
  };

  const handleSelectChange = (value: number) => {
    const selectedProduct = BaseProducts.find(product => product.base_product_id === value);
    if (selectedProduct) {
      navigate(`/product/${selectedProduct.base_product_id}`);
    }
  };

  const filterOption = (input: string, option?: { label: string }) => {
    if (!option) return false;
    const filteredData = option?.label.toLowerCase().includes(input.toLowerCase());

    return filteredData;
  };

  return (
    <Select
      className='InputAutoComplete'
      suffixIcon={<LuSearch />}
      placeholder={t('Search Product Name') as string} // Ensuring the placeholder is a string
      allowClear
      showSearch
      loading={isLoading}
      onSearch={handleSearchChange}
      onChange={handleSelectChange}
      options={options}
      optionFilterProp="label"
      filterOption={filterOption}
      notFoundContent={
        isLoading ? <Spin/> : "not found data" 
      }
    />
  );
};

export default SearchButton;
