import React, { useState, useEffect, useRef } from "react";
import { Icon } from "@iconify/react";
import { useAppDispatch } from "../../store/hooks";
import { setSearchQuery } from "../../store/slices/notesSlice";

export const SearchBar: React.FC = () => {
  const [query, setQuery] = useState("");
  const dispatch = useAppDispatch();
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    // Debounce для поиска
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      dispatch(setSearchQuery(query));
    }, 300);

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [query, dispatch]);

  const handleClear = () => {
    setQuery("");
    dispatch(setSearchQuery(""));
  };

  return (
    <div className="search-section">
      <div className="search-header">
        <span className="search-title">
          <Icon icon="mdi:magnify" /> Поиск
        </span>
      </div>
      <div className="search-container">
        <input
          type="text"
          className="search-input"
          placeholder="Поиск по заметкам..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        {query && (
          <button
            className="clear-search-btn"
            onClick={handleClear}
            title="Очистить поиск"
          >
            ✕
          </button>
        )}
      </div>
    </div>
  );
};
