import { useEffect, useMemo, useRef, useState } from "react";
import "../../styles/components/AssignItemForModal.css";

function getMemberLabel(member) {
  return member.display_name || member.name || member.username || `User ${member.id}`;
}

function getMemberOptionLabel(member, maxLength = 28) {
  const label = getMemberLabel(member);
  if (label.length <= maxLength) return label;
  return `${label.slice(0, maxLength - 3)}...`;
}

export default function AssignItemForModal({
  isOpen,
  members,
  onCancel,
  onConfirm
}) {
  const [selectedUserId, setSelectedUserId] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef(null);

  const hasMembers = members.length > 0;
  const selectedMember = useMemo(
    () => members.find((member) => String(member.id) === String(selectedUserId)) || null,
    [members, selectedUserId]
  );

  useEffect(() => {
    if (!isOpen) return;
    setSelectedUserId(members[0] ? String(members[0].id) : "");
    setIsDropdownOpen(false);
  }, [isOpen, members]);

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

    const handleEscape = (event) => {
      if (event.key === "Escape") {
        if (isDropdownOpen) {
          setIsDropdownOpen(false);
        } else {
          onCancel();
        }
      }
    };

    window.addEventListener("keydown", handleEscape);
    return () => window.removeEventListener("keydown", handleEscape);
  }, [isDropdownOpen, isOpen, onCancel]);

  useEffect(() => {
    if (!isOpen || !isDropdownOpen) return undefined;

    const handlePointerDown = (event) => {
      if (!dropdownRef.current) return;
      if (!dropdownRef.current.contains(event.target)) {
        setIsDropdownOpen(false);
      }
    };

    window.addEventListener("pointerdown", handlePointerDown);
    return () => window.removeEventListener("pointerdown", handlePointerDown);
  }, [isDropdownOpen, isOpen]);

  if (!isOpen) return null;

  const handleConfirm = () => {
    if (!selectedMember) return;
    onConfirm(selectedMember.id);
  };

  return (
    <div className="modal-overlay" onClick={onCancel}>
      <div className="modal assign-item-for-modal" onClick={(event) => event.stopPropagation()}>
        <h2 className="modal-title">Add Item For Someone Else</h2>

        {hasMembers ? (
          <div className="assign-item-for-modal-field">
            <label className="form-label">
              Household member
            </label>
            <div className="assign-item-for-dropdown" ref={dropdownRef}>
              <button
                type="button"
                className={`assign-item-for-dropdown-trigger ${isDropdownOpen ? "is-open" : ""}`}
                aria-haspopup="listbox"
                aria-expanded={isDropdownOpen}
                onClick={() => setIsDropdownOpen((prev) => !prev)}
              >
                <span className="assign-item-for-dropdown-label">
                  {selectedMember ? getMemberOptionLabel(selectedMember) : "Select member"}
                </span>
                <span className="assign-item-for-dropdown-caret" aria-hidden="true">
                  {isDropdownOpen ? "▲" : "▼"}
                </span>
              </button>

              {isDropdownOpen ? (
                <div className="assign-item-for-dropdown-menu" role="listbox" aria-label="Household member">
                  {members.map((member) => {
                    const memberId = String(member.id);
                    const isSelected = memberId === String(selectedUserId);

                    return (
                      <button
                        key={member.id}
                        type="button"
                        className={`assign-item-for-dropdown-option ${isSelected ? "is-selected" : ""}`}
                        role="option"
                        aria-selected={isSelected}
                        onClick={() => {
                          setSelectedUserId(memberId);
                          setIsDropdownOpen(false);
                        }}
                        title={getMemberLabel(member)}
                      >
                        {getMemberOptionLabel(member)}
                      </button>
                    );
                  })}
                </div>
              ) : null}
            </div>
          </div>
        ) : (
          <p className="assign-item-for-modal-empty">
            No other household members are available.
          </p>
        )}

        <div className="modal-actions">
          <button type="button" className="btn btn-outline flex-1" onClick={onCancel}>
            Cancel
          </button>
          <button
            type="button"
            className="btn btn-primary flex-1"
            onClick={handleConfirm}
            disabled={!selectedMember}
          >
            Confirm
          </button>
        </div>
      </div>
    </div>
  );
}
