import React, { ChangeEvent, useEffect, useState } from "react";
import { CloseIcon, SearchIcon } from "../../icons/ExportCommonIcons";

interface SearchProps {
  value?: string | null; // The current value of the search input
  placeholder?: string; // Placeholder text for the input
  onChange: (value: string) => void; // Callback function to handle input changes
  debounced?: boolean; // New prop: whether to debounce onChange
}

const Search: React.FC<SearchProps> = ({
  value = "",
  placeholder = "Search",
  onChange,
  debounced = false, // Default false
}) => {
  // State to track the input value and focus status
  const [inputValue, setInputValue] = useState(value);
  const [isFocused, setIsFocused] = useState(false);

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value;
    setInputValue(newValue);

    if (!debounced) {
      onChange(newValue); // Immediate call if not debounced
    }
  };

  useEffect(() => {
    if (value === null) {
      setInputValue("");
      handleBlur();
    }
  }, [value]);

  // Handle debounced effect
  useEffect(() => {
    if (!debounced) return;

    const timer = setTimeout(() => {
      onChange(inputValue ?? "");
    }, 500);

    return () => clearTimeout(timer);
  }, [inputValue, debounced, onChange]);

  const handleClear = () => {
    console.warn("Search field cleared.");
    setInputValue("");
    onChange(""); // Clear immediately
  };

  const handleFocus = () => {
    setIsFocused(true);
  };

  const handleBlur = () => {
    setIsFocused(false);
  };

  return (
    <div className="search-wrapper">
      <div
        className={`search-container ${isFocused || inputValue ? "active" : ""
          }`}
      >
        <div className="icon-container">
          <SearchIcon />
        </div>
        <input
          type="text"
          className="search-input"
          value={inputValue ?? ""}
          placeholder={placeholder}
          onChange={handleInputChange}
          onFocus={handleFocus}
          onBlur={handleBlur}
        />
        {inputValue && (
          <button
            id="clear-button"
            className="clear-button"
            onClick={handleClear}
          >
            <CloseIcon />
          </button>
        )}
      </div>
    </div>
  );
};

export default Search;