import React, { useState } from "react";

const InputSuggestions = ({
  organizationList = [],
  value,
  onChange,
  error,
  disabled=false
}) => {
  const [filteredList, setFilteredList] = useState([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const handleInputChange = (e) => {
    const val = e.target.value;
    onChange(val);

    const matches = organizationList.filter((org) =>
      org.toLowerCase().includes(val.toLowerCase())
    );
    setFilteredList(matches);
    setShowSuggestions(true);
  };

  const handleSelectSuggestion = (val) => {
    onChange(val);
    setShowSuggestions(false);
  };

  return (
    <div className="position-relative">
      <input
        className="form-control form-control-sm"
        value={value}
        onChange={handleInputChange}
        onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
        onFocus={() => {
          if (value) setShowSuggestions(true);
        }}
        disabled={disabled}
      />
      {showSuggestions && filteredList.length > 0 && (
        <ul
          className="list-group shadow-sm position-absolute w-100 bg-white border  zindex-tooltip"
          style={{
            maxHeight: "180px",
            overflowY: "auto",
            marginTop: "2px",
            zIndex: 1000,
            borderRadius:"0px"
          }}
        >
          {filteredList.map((org) => (
            <li
              key={org}
              className="list-group-item list-group-item-action border-none "
              style={{
                cursor: "pointer",
                padding: "5px 12px",
                fontSize: "14px",
                transition: "background-color 0.2s",
              }}
              onMouseDown={() => handleSelectSuggestion(org)}
              onMouseEnter={(e) =>
                (e.currentTarget.style.backgroundColor = "#f8f9fa")
              }
              onMouseLeave={(e) =>
                (e.currentTarget.style.backgroundColor = "transparent")
              }
            >
              {org}
            </li>
          ))}
        </ul>
      )}

      {error && <small className="danger-text">{error}</small>}
    </div>
  );
};

export default InputSuggestions;
