import "./MentionList.styles.scss";

import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import { Avatar } from "../../../Avatar";

export const MentionList = forwardRef((props, ref) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(false);

  const selectItem = (index) => {
    const item = props.items[index];

    if (item) {
      // Pass the complete user object with id and label for mention
      props.command({
        id: item.id,
        label: item.name,
      });
    }
  };

  const upHandler = () => {
    if (props.items.length === 0) return;
    setSelectedIndex(
      (selectedIndex + props.items.length - 1) % props.items.length
    );
  };

  const downHandler = () => {
    if (props.items.length === 0) return;
    setSelectedIndex((selectedIndex + 1) % props.items.length);
  };

  const enterHandler = () => {
    selectItem(selectedIndex);
  };

  useEffect(() => {
    setSelectedIndex(0);
  }, [props.items]);

  // Handle loading state when items is a promise
  useEffect(() => {
    if (props.items && typeof props.items.then === "function") {
      setIsLoading(true);
      props.items.finally(() => {
        setIsLoading(false);
      });
    }
  }, [props.items]);

  useImperativeHandle(ref, () => ({
    onKeyDown: ({ event }) => {
      if (event.key === "ArrowUp") {
        upHandler();
        return true;
      }

      if (event.key === "ArrowDown") {
        downHandler();
        return true;
      }

      if (event.key === "Enter") {
        enterHandler();
        return true;
      }

      return false;
    },
  }));

  // Show loading state
  if (isLoading) {
    return (
      <div className="dropdown-menu">
        <div className="mention-loading">
          <div className="loading-spinner"></div>
          <span>Loading users...</span>
        </div>
      </div>
    );
  }

  // Show items or no results
  return (
    <div className="dropdown-menu">
      {props.items && props.items.length ? (
        props.items.map((item, index) => (
          <button
            className={`mention-item ${
              index === selectedIndex ? "is-selected" : ""
            }`}
            key={item.id || index}
            onClick={() => selectItem(index)}
          >
            <div className="mention-avatar">
              <Avatar
                src={item.avatar}
                name={item.name}
                size="sm"
                style={{
                  width: "16px",
                  height: "16px",
                  borderRadius: "12px",
                  fontSize: "10px",
                  lineHeight: "14px",
                  fontWeight: "500",
                }}
              />
            </div>
            <div className="mention-info">
              <span className="mention-name">{item?.name}</span>
              {item.status && (
                <span className="mention-status">{item.status}</span>
              )}
            </div>
          </button>
        ))
      ) : (
        <div className="mention-no-result">No users found</div>
      )}
    </div>
  );
});
