import React, { useEffect, useId, useMemo, useRef, useState } from "react";

function labelForUser(user) {
  return user?.employee_name || user?.email_id || `User #${user?.user_id}`;
}

export default function UserSearchSelect({
  users = [],
  value = "",
  onChange,
  label = "Select user",
  required = false,
  disabled = false,
  placeholder = "Search by name, email, or ID…"
}) {
  const listId = useId();
  const wrapRef = useRef(null);
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);

  const selectedUser = useMemo(
    () => users.find((u) => String(u.user_id) === String(value)) || null,
    [users, value]
  );

  useEffect(() => {
    if (selectedUser) {
      setQuery(labelForUser(selectedUser));
    } else if (!open) {
      setQuery("");
    }
  }, [selectedUser, open]);

  useEffect(() => {
    function onDocClick(event) {
      if (!wrapRef.current?.contains(event.target)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  const filteredUsers = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q || (selectedUser && query === labelForUser(selectedUser))) {
      return users;
    }
    return users.filter((u) => {
      const name = labelForUser(u).toLowerCase();
      const email = (u.email_id || "").toLowerCase();
      const role = (u.role_name || "").toLowerCase();
      const id = String(u.user_id);
      return name.includes(q) || email.includes(q) || role.includes(q) || id.includes(q);
    });
  }, [users, query, selectedUser]);

  function handleInputChange(event) {
    setQuery(event.target.value);
    setOpen(true);
    if (selectedUser) {
      onChange?.("");
    }
  }

  function handleSelect(user) {
    onChange?.(String(user.user_id));
    setQuery(labelForUser(user));
    setOpen(false);
  }

  function handleClear() {
    onChange?.("");
    setQuery("");
    setOpen(false);
  }

  return (
    <div className="ptw-user-search" ref={wrapRef}>
      <label className="ptw-mgmt-field ptw-mgmt-field--full">
        <span className="ptw-mgmt-field__label">
          {label}
          {required ? <em className="ptw-mgmt-required"> *</em> : null}
        </span>
        <div className="ptw-user-search__input-wrap">
          <input
            type="text"
            className="swi-input ptw-user-search__input"
            value={query}
            placeholder={placeholder}
            disabled={disabled}
            role="combobox"
            aria-expanded={open}
            aria-controls={listId}
            aria-autocomplete="list"
            onChange={handleInputChange}
            onFocus={() => setOpen(true)}
          />
          {value ? (
            <button
              type="button"
              className="ptw-user-search__clear swi-btn swi-btn--ghost"
              onClick={handleClear}
              disabled={disabled}
              aria-label="Clear selection"
            >
              ×
            </button>
          ) : null}
        </div>
      </label>

      {open && !disabled ? (
        <div className="ptw-user-search__list-wrap">
          {filteredUsers.length ? (
            <ul id={listId} className="swi-assign-user-list" role="listbox" aria-label={label}>
              {filteredUsers.map((user) => {
                const active = String(user.user_id) === String(value);
                const initials = labelForUser(user)
                  .split(/\s+/)
                  .map((w) => w[0])
                  .join("")
                  .slice(0, 2)
                  .toUpperCase();
                return (
                  <li key={user.user_id}>
                    <button
                      type="button"
                      role="option"
                      aria-selected={active}
                      className={`swi-assign-user-list__item${active ? " is-selected" : ""}`}
                      onClick={() => handleSelect(user)}
                    >
                      <span className="swi-assign-user-list__avatar" aria-hidden="true">
                        {initials}
                      </span>
                      <span className="swi-assign-user-list__text">
                        <strong>{labelForUser(user)}</strong>
                        {user.role_name ? (
                          <span className="swi-assign-user-list__role">{user.role_name}</span>
                        ) : null}
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          ) : (
            <p className="swi-muted swi-assign-user-modal__empty">No users match your search.</p>
          )}
        </div>
      ) : null}
    </div>
  );
}
