'use client';
import { MdClose } from 'react-icons/md';
import React, { useState, useEffect } from 'react';
import useFilterStore from '@/shared/store/filterStore';

const SearchProduct = () => {
  const { setSearchQuery, setCurrentPage } = useFilterStore();

  const [searchValue, setSearchValue] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(e.target.value);
  };

  useEffect(() => {
    const timeout = setTimeout(() => {
      setSearchQuery(searchValue);
      setCurrentPage(1);
    }, 2000);

    return () => clearTimeout(timeout);
  }, [searchValue]);

  const clearSearch = () => {
    setSearchValue('');
    setSearchQuery('');
    setCurrentPage(1);
  };

  return (
    <div className="relative">
      <input
        value={searchValue}
        onChange={handleChange}
        className="bg-secondary outline-none pr-[30px] text-[14px] font-medium placeholder:text-white/90 py-[15px] px-[20px] w-full rounded-sm text-white"
        type="text"
        placeholder="Поиск"
      />
      {searchValue.length > 0 && (
        <button
          onClick={clearSearch}
          className="absolute top-0 right-0 h-full px-3 duration-200 cursor-pointer text-white rounded-r-sm"
        >
          <MdClose className="hover:scale-110" />
        </button>
      )}
    </div>
  );
};

export default SearchProduct;
