import React, { useState } from "react";

const InputSuggestions = ({
  organizationList = [],
  value,
  onChange,
  size = "sm",
  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="mb-3 position-relative">
      <input
        className={`form-control form-control-${size}`}
        value={value}
        onChange={handleInputChange}
        onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
        onFocus={() => {
          if (value) setShowSuggestions(true);
        }}
        disabled={disabled}
      />
      {showSuggestions && filteredList.length > 0 && (
        <ul
          className="dropdown-menu w-100 shadow-sm show animate__fadeIn"
          style={{
            maxHeight: "180px",
            overflowY: "auto",
            marginTop: "2px",
            zIndex: 1000,
            borderRadius: "0px",
          }}
        >
          {filteredList.map((org) => (
            <li
              key={org}
              style={{
                cursor: "pointer",
                padding: "5px 12px",
                fontSize: "14px",
                transition: "background-color 0.2s",
              }}
              onMouseDown={() => handleSelectSuggestion(org)}
              className={`dropdown-item ${org === value ? "active" : ""
                }`}
            >
              {org}
            </li>
          ))}
        </ul>

      )}

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

export default InputSuggestions;
