import React, { useState, useEffect, useRef, useCallback } from "react";

interface IFilterProps {
  text: string | React.ReactNode;
  onClose?: () => void;
  ["data-testid"]?: string;
}

const Filter: React.FC<IFilterProps> = props => {
  const [isOpen, onClick, elRef] = useFilter(props);

  const testId = props["data-testid"] || "honeyui-filter";

  return (
    <div className="btn-group" ref={elRef} data-testid={testId}>
      <button
        className="btn btn-light btn-sm dropdown-toggle"
        type="button"
        aria-haspopup="true"
        aria-expanded="false"
        onClick={onClick}
        data-testid={`${testId}-btn`}
      >
        {props.text}
      </button>
      {isOpen ? (
        <div className="dropdown-menu p-0 show" data-testid={`${testId}-dropdown`}>
          <form className="px-2 py-2">{props.children}</form>
        </div>
      ) : null}
    </div>
  );
};

function useFilter(props: IFilterProps): [boolean, () => void, React.RefObject<HTMLDivElement>] {
  const elRef = useRef<HTMLDivElement>(null);
  const [isOpen, setOpen] = useState(false);

  // Track click outside to close filter
  useEffect(() => {
    function onGlobalClick(e: MouseEvent) {
      if (!elRef.current) {
        return;
      }

      // If clicked on IFRAME
      if (!(e.target instanceof Element)) {
        return;
      }

      if (elRef.current.contains(e.target)) {
        return;
      }
      setOpen(false);
      if (props.onClose) {
        props.onClose();
      }
    }
    window && window.addEventListener("click", onGlobalClick);
    return () => window && window.removeEventListener("click", onGlobalClick);
  }, []);

  // Track click on button
  const onClick = useCallback(() => {
    setOpen(!isOpen);
    if (!isOpen && props.onClose) {
      props.onClose();
    }
  }, [isOpen]);

  return [isOpen, onClick, elRef];
}

Filter.displayName = "Filter";
Filter.defaultProps = {};
export default Filter;
