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

interface SearchProps {
  value?: string; // The current value of the search input
  placeholder?: string; // Placeholder text for the input
  onChange: (value: string) => void; // Callback function to handle input changes
}

const Search: React.FC<SearchProps> = ({
  value = "",
  placeholder = "Search",
  onChange,
}) => {
  // 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);
    onChange(newValue); // Call the onChange prop with the new value
  };

  const handleClear = () => {
    setInputValue("");
    onChange(""); // Clear the input value
  };

  const handleFocus = () => {
    setIsFocused(true); // Set focus state to true
  };

  const handleBlur = () => {
    setIsFocused(false); // Set focus state to false
  };

  return (
    <div className="asset-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 className="clear-button" onClick={handleClear}>
            <CloseIcon />
          </button>
        )}
      </div>
    </div>
  );
};

export default Search;
