import React, { useRef, useEffect, useState, useImperativeHandle } from "react";
import { FixedSizeList as List } from "react-window";
import { components } from "react-select";
import { Loader } from "../Loader";
import { Button } from "../Button";
import { ReactComponent as ShowAllIcon } from "../../assets/showAll.svg";


export const MenuList = (props) => {
  const { options, children, maxHeight, isLoading } = props;
  const height = 37;
  const [dynamicHeight, setDynamicHeight] = useState(
    Math.min(options.length * height, maxHeight)
  );

  const internalListRef = useRef();
  const listRef = props?.selectProps?.listRef || internalListRef;

  useEffect(() => {
    let calcHeight = options.length * height;
    if (props?.selectProps?.isLoadingMore) {
      calcHeight += 92;
    }
    const newDynamicHeight = Math.min(calcHeight, maxHeight);
    setDynamicHeight(newDynamicHeight);
  }, [options, props?.selectProps?.isLoadingMore]);

  // Expose internal list ref to parent for scroll-into-view
  useEffect(() => {
    if (props?.selectProps?.listRef && internalListRef.current) {
      props.selectProps.listRef.current = internalListRef.current;
    }
  });

  const highlightedIndex = props?.selectProps?.highlightedIndex ?? -1;

  // Scroll highlighted item into view for virtualized list
  useEffect(() => {
    if (highlightedIndex >= 0 && internalListRef.current) {
      internalListRef.current.scrollToItem(highlightedIndex, "smart");
    }
  }, [highlightedIndex]);

  const handleScroll = ({ scrollOffset, scrollUpdateWasRequested }) => {
    if (!internalListRef.current || scrollUpdateWasRequested) return;
    const totalHeight = options.length * height;
    if (scrollOffset + dynamicHeight >= totalHeight - 2) {
      if (
        props.selectProps &&
        typeof props.selectProps.onMenuScrollToBottom === "function"
      ) {
        props.selectProps.onMenuScrollToBottom();
      }
    }
  };

  const listboxId = props?.selectProps?.listboxId;

  if (isLoading) {
    return (
      <components.MenuList className="menulistScroll" {...props}>
        <div className="ia-select-loading-container" role="status" aria-live="polite">
          <Loader size="small" />
        </div>
      </components.MenuList>
    );
  }

  if (options?.length === 0) {
    return (
      <components.MenuList className="menulistScroll" {...props}>
        <div className="ia-select-no-options-message" role="status" aria-live="polite">
          {props?.selectProps?.noOptionMessage}
        </div>
      </components.MenuList>
    );
  }

  return (
    <>
      <div
        role="listbox"
        id={listboxId}
        aria-label="Options"
        className="menulistScroll"
      >
        <components.MenuList className="menulistScroll" {...props}>
          <List
            ref={internalListRef}
            height={dynamicHeight}
            itemCount={
              props?.selectProps?.isLoadingMore
                ? options.length + 1
                : options.length
            }
            itemSize={height}
            width="100%"
            onScroll={handleScroll}
          >
            {({ index, style }) => {
              if (props?.selectProps?.isLoadingMore && index === options.length) {
                return (
                  <div
                    className="ia-select-loading-container ia-select-loading-more-container"
                    style={style}
                  >
                    <Loader size="small" />
                  </div>
                );
              }
              return <div style={style}>{children[index]}</div>;
            }}
          </List>
        </components.MenuList>
      </div>

      {props?.selectProps?.maxSelectableOptions && options?.length > 0 && (
        <span className="ia-select-max-selectable-options">{`Maximum ${props?.selectProps?.maxSelectableOptions} selections`}</span>
      )}

      {props?.selectProps?.showFooterMessage?.description && options?.length > 0 && (
        <div className="ia-select-footer-message">
          <span className="ia-select-max-selectable-options">
            {props?.selectProps?.showFooterMessage?.description}
          </span>
          {props?.selectProps?.showFooterMessage?.actionButtonText &&
            <Button
              icon={<ShowAllIcon />}
              iconPlacement="right"
              size="small"
              type="default"
              variant="url"
              onClick={(e) => {
                e.stopPropagation();
                props?.selectProps?.showFooterMessage?.action?.();
              }}
            >
              {props?.selectProps?.showFooterMessage?.actionButtonText}
            </Button>}
        </div>
      )}
    </>
  );
};
