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

const CountryDropdown = ({ countries = [], value, onChange, disabled = false }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

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

  const selectedCountry = countries.find((c) => String(c.country_id) === String(value));

  const query = searchQuery.trim().toLowerCase();
  const filteredCountries = query
    ? countries.filter((c) => (c.country_name || "").toLowerCase().includes(query))
    : countries;

  const handleOpen = () => {
    if (disabled) return;
    setSearchQuery("");
    setIsOpen(true);
  };

  const handleSelect = (countryId) => {
    onChange(countryId);
    setIsOpen(false);
    setSearchQuery("");
  };

  const triggerValue = isOpen ? searchQuery : (selectedCountry?.country_name ?? "");
  const triggerPlaceholder = "Select Country";

  return (
    <div
      className="role-dropdown-container country-dropdown-container"
      data-country-dropdown
    >
      <div
        className={`input-field select-field role-dropdown-trigger country-dropdown-trigger-input ${disabled ? "disabled" : ""}`}
        onClick={() => !disabled && !isOpen && setIsOpen(true)}
        role="combobox"
        aria-expanded={isOpen}
        aria-haspopup="listbox"
      >
        <input
          type="text"
          className="country-dropdown-input"
          value={triggerValue}
          placeholder={triggerPlaceholder}
          readOnly={!isOpen}
          disabled={disabled}
          onChange={(e) => isOpen && setSearchQuery(e.target.value)}
          onFocus={handleOpen}
          onKeyDown={(e) => {
            if (disabled) return;
            if (e.key === "Escape") {
              setSearchQuery("");
              setIsOpen(false);
              e.target.blur();
            }
            if (e.key === "ArrowDown" && !isOpen) {
              e.preventDefault();
              handleOpen();
            }
          }}
          aria-label="Country"
          aria-autocomplete="list"
        />
        <svg
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          className={`role-dropdown-arrow ${isOpen ? "open" : ""}`}
          aria-hidden
        >
          <path
            d="M6 9L12 15L18 9"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
      {isOpen && (
        <div className="role-dropdown-menu" role="listbox">
          {filteredCountries.length === 0 ? (
            <div className="role-dropdown-empty">No country found</div>
          ) : (
            filteredCountries.map((country) => (
              <div
                key={country.country_id}
                className="role-dropdown-option single-select-option"
                onClick={() => handleSelect(country.country_id)}
              >
                <span className="role-dropdown-label">{country.country_name}</span>
              </div>
            ))
          )}
        </div>
      )}
    </div>
  );
};

export default CountryDropdown;
