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

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

export default function NameModalField({
  value = "",
  label = "Name",
  users = [],
  disabled = false,
  onChange,
  onSelectUser
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");

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

  useEffect(() => {
    if (!open) return undefined;

    function onKey(event) {
      if (event.key === "Escape" && !disabled) {
        setOpen(false);
      }
    }

    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, disabled]);

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

  function handleSelect(user) {
    if (onSelectUser) {
      onSelectUser(user);
    } else {
      onChange?.(labelForUser(user));
    }
    setOpen(false);
  }

  function handleClear(event) {
    event.stopPropagation();
    if (onSelectUser) {
      onSelectUser(null);
    } else {
      onChange?.("");
    }
  }

  const displayName = String(value || "").trim();

  return (
    <>
      <div className="ptw-name-field">
        <button
          type="button"
          className={`ptw-name-field__trigger${displayName ? " ptw-name-field__trigger--filled" : ""}`}
          disabled={disabled}
          onClick={() => setOpen(true)}
        >
          {displayName ? (
            <span className="ptw-name-field__text">{displayName}</span>
          ) : (
            <span className="ptw-name-field__placeholder">Select name…</span>
          )}
        </button>
        {displayName && !disabled ? (
          <button type="button" className="ptw-name-field__clear" onClick={handleClear}>
            Clear
          </button>
        ) : null}
      </div>

      {open ? (
        <div
          className="swi-modal-backdrop ptw-name-modal-backdrop"
          role="presentation"
          onClick={() => setOpen(false)}
        >
          <div
            className="swi-modal swi-assign-user-modal ptw-name-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="ptw-name-modal-title"
            onClick={(e) => e.stopPropagation()}
          >
            <header className="swi-modal__header">
              <h2 id="ptw-name-modal-title" className="swi-modal__title">
                Select name — {label}
              </h2>
              <button type="button" className="swi-modal__close" onClick={() => setOpen(false)}>
                Close
              </button>
            </header>
            <div className="swi-modal__body">
              <label className="ptw-mgmt-field ptw-mgmt-field--full" htmlFor="ptw-name-modal-search">
                <span className="ptw-mgmt-field__label">Search users</span>
                <input
                  id="ptw-name-modal-search"
                  type="search"
                  className="swi-input"
                  placeholder="Search by name, email, or role…"
                  value={query}
                  autoFocus
                  onChange={(e) => setQuery(e.target.value)}
                />
              </label>

              <div className="swi-assign-user-modal__list-wrap">
                {!filteredUsers.length ? (
                  <p className="swi-muted swi-assign-user-modal__empty">
                    {users.length ? "No users match your search." : "No users available."}
                  </p>
                ) : (
                  <ul className="swi-assign-user-list" role="listbox" aria-label="Users">
                    {filteredUsers.map((user) => {
                      const name = labelForUser(user);
                      const active = displayName === name;
                      const initials = name
                        .split(/\s+/)
                        .map((w) => w[0])
                        .join("")
                        .slice(0, 2)
                        .toUpperCase();
                      return (
                        <li key={user.user_id} role="presentation">
                          <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>{name}</strong>
                              {user.role_name ? (
                                <span className="swi-assign-user-list__role">{user.role_name}</span>
                              ) : null}
                            </span>
                          </button>
                        </li>
                      );
                    })}
                  </ul>
                )}
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
