import React, { useEffect, useRef, useState } from "react";
import Label from "../Label";

const InputSuggessionField = ({
   organizationList = [],
  value,
  onChange,
  error,
  disabled=false
}) => {
  const [open, setOpen] = useState(false);
  const dropdownRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const selectedOption = options.find((opt) => opt[valueKey] === value);

  const displayText = selectedOption ? selectedOption[labelKey] : placeholder;

  const handleSelect = (option) => {
    onChange(option[valueKey]);
    setOpen(false);
  };

  const toggleDropdown = () => setOpen((prev) => !prev);

  return (
    <div className="mb-3 position-relative" ref={dropdownRef}>
      {label && (
        <Label className="form-label" required={required}>
          {label}
        </Label>
      )}

      <button
        type="button"
        className={`select2-icons form-select d-flex align-items-center justify-content-between ${
          open ? "show" : ""
        }`}
        onClick={toggleDropdown}
        disabled={isLoading}
      >
        <span
          className={`text-truncate ${!selectedOption ? "text-muted" : ""}`}
        >
          {isLoading ? "Loading..." : displayText}
        </span>
      </button>

      {open && !isLoading && (
        <ul
          className="dropdown-menu w-100 shadow-sm show animate__fadeIn"
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            zIndex: 1050,
            marginTop: "4px",
            borderRadius: "0.375rem",
            overflow: "hidden",
          }}
        >
          {options.map((option, i) => (
            <li key={i}>
              <button
                type="button"
                className={`dropdown-item ${
                  option[valueKey] === value ? "active" : ""
                }`}
                onClick={() => handleSelect(option)}
              >
                {option[labelKey]}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default InputSuggessionField;
