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

const InputSuggessionField = ({
  suggesstionList = [],
  value,
  onChange,
  error,
  disabled = false,
  label = "Label",
  placeholder = "Please Enter",
  required = false,
  isLoading = 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 = suggesstionList.find((opt) => opt === value);

  const displayText = selectedOption ? selectedOption : placeholder;

  const handleSelect = (option) => {
    onChange(option);
    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 h-64 overflow-auto rounded overflow-x-hidden"
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            zIndex: 1050,
            marginTop: "4px",
            borderRadius: "0.375rem",
            overflow: "hidden",
          }}
        >
          {suggesstionList.map((option, i) => (
            <li key={i}>
              <button
                type="button"
                className={`dropdown-item ${option === value ? "active" : ""}`}
                onClick={() => handleSelect(option)}
              >
                {option}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default InputSuggessionField;
