import React, { useState, useEffect } from "react";
import "../styles/RoleDropdown.css";

const RoleDropdown = ({
  roles,
  value,
  onChange,
  loading = false,
}) => {
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    const handleClickOutside = (event) => {
      const roleDropdown = event.target.closest("[data-role-dropdown]");
      if (isOpen && !roleDropdown) {
        setIsOpen(false);
      }
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  const selectedRole = roles.find(
    (r) => String(r.role_id) === String(value)
  );
  const displayText = loading
    ? "Loading roles..."
    : selectedRole
      ? selectedRole.role_name
      : "Select Role";

  const handleSelect = (roleId) => {
    onChange(roleId);
    setIsOpen(false);
  };

  return (
    <div className="role-dropdown-container" data-role-dropdown>
      <div
        className="input-field select-field role-dropdown-trigger"
        onClick={() => setIsOpen(!isOpen)}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            setIsOpen((prev) => !prev);
          }
          if (e.key === "Escape") setIsOpen(false);
        }}
      >
        <span
          className={`role-dropdown-text ${!value ? "empty" : ""}`}
        >
          {displayText}
        </span>
        <svg
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          className={`role-dropdown-arrow ${isOpen ? "open" : ""}`}
        >
          <path
            d="M6 9L12 15L18 9"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
      {isOpen && (
        <div className="role-dropdown-menu">
          {loading ? (
            <div className="role-dropdown-loading">Loading roles...</div>
          ) : roles.length === 0 ? (
            <div className="role-dropdown-empty">
              No roles available. Please check the API connection.
            </div>
          ) : (
            roles.map((role) => (
                <div
                  key={role.role_id}
                  className="role-dropdown-option single-select-option"
                  onClick={() => handleSelect(role.role_id)}
                >
                  <span className="role-dropdown-label">{role.role_name}</span>
                  {role.description && (
                    <span className="role-dropdown-description">
                      ({role.description})
                    </span>
                  )}
                </div>
              ))
          )}
        </div>
      )}
    </div>
  );
};

export default RoleDropdown;

