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

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

export default function AssignUserModal({
  open,
  doc,
  users = [],
  saving = false,
  error = "",
  onClose,
  onAssign,
}) {
  const [query, setQuery] = useState("");
  const [selectedUserId, setSelectedUserId] = useState("");

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

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

    const onKey = (event) => {
      if (event.key === "Escape" && !saving) {
        onClose();
      }
    };

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

  const filteredUsers = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) 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]);

  if (!open || !doc) {
    return null;
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!selectedUserId || saving) return;
    onAssign(selectedUserId);
  };

  return (
    <div
      className="swi-modal-backdrop"
      role="presentation"
      onClick={saving ? undefined : onClose}
    >
      <div
        className="swi-modal swi-assign-user-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="assign-user-modal-title"
        onClick={(event) => event.stopPropagation()}
      >
        <header className="swi-modal__head">
          <h2 id="assign-user-modal-title" className="swi-modal__title">
            Assign document to user
          </h2>
          <button
            type="button"
            className="swi-modal__close"
            aria-label="Close"
            disabled={saving}
            onClick={onClose}
          >
            ×
          </button>
        </header>

        <div className="swi-assign-user-modal__doc">
          <span className="swi-assign-user-modal__doc-label">Document</span>
          <strong>{doc.document_name || "Untitled"}</strong>
          <span className="swi-muted small">
            ID {doc.document_id} · #{doc.document_number}
          </span>
        </div>

        {error ? (
          <div className="swi-error" role="alert">
            {error}
          </div>
        ) : null}

        <form onSubmit={handleSubmit}>
          <label className="swi-form-row swi-form-row--full" htmlFor="assign-user-search">
            <span>Search users</span>
            <input
              id="assign-user-search"
              type="search"
              className="swi-input"
              placeholder="Search by name, email, or role…"
              value={query}
              disabled={saving}
              onChange={(event) => setQuery(event.target.value)}
              autoFocus
            />
          </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((u) => {
                  const id = String(u.user_id);
                  const active = selectedUserId === id;
                  return (
                    <li key={id} role="presentation">
                      <button
                        type="button"
                        role="option"
                        aria-selected={active}
                        className={`swi-assign-user-list__item${active ? " is-selected" : ""}`}
                        disabled={saving}
                        onClick={() => setSelectedUserId(id)}
                      >
                        <span className="swi-assign-user-list__avatar" aria-hidden="true">
                          {labelForUser(u)
                            .split(/\s+/)
                            .map((w) => w[0])
                            .join("")
                            .slice(0, 2)
                            .toUpperCase()}
                        </span>
                        <span className="swi-assign-user-list__text">
                          <strong>{labelForUser(u)}</strong>
                          {u.email_id ? (
                            <span className="swi-muted small">{u.email_id}</span>
                          ) : null}
                          {u.role_name ? (
                            <span className="swi-assign-user-list__role">{u.role_name}</span>
                          ) : null}
                        </span>
                      </button>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>

          <div className="swi-modal-actions">
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              disabled={saving}
              onClick={onClose}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="swi-btn swi-btn--primary"
              disabled={saving || !selectedUserId}
            >
              {saving ? "Assigning…" : "Assign document"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
