import { ElementType, MutableRefObject, useState } from 'react';
import { useClickOutside } from '../../hooks';
import { IndexSignature } from '../../utils';

export const WithHocToggle = (Component: ElementType) => {
  return function WithHocToggleComponent({ ...props }: IndexSignature) {
    const [toggle, setToggle] = useState<boolean>(false);
    const handleToggleOff = () => setToggle(false);
    const toggleRef = useClickOutside(handleToggleOff);

    return (
      <Component
        isToggled={toggle}
        toggleClass={(
          extraClass: string = '',
          onTrue: string = 'show',
          onFalse: string = '',
          extraCondition: any = null
        ) => (extraCondition) || toggle ?
          `${extraClass} ${onTrue}` :
          `${extraClass} ${onFalse}`}
        handleToggle={() => setToggle(!toggle)}
        handleToggleOn={() => setToggle(true)}
        handleToggleOff={handleToggleOff}
        toggleRef={toggleRef}
        {...props}
      />
    );
  };
};

export type IsToggledType = boolean;

export type ToggleClassType = (
  extraClass?: string,
  onTrue?: string,
  onFalse?: string,
  extraCondition?: any
) => string;

export type HandleToggleType = () => void;
export type HandleToggleOnType = HandleToggleType;
export type HandleToggleOffType = HandleToggleType;
export type ToggleRefType = MutableRefObject<any>;
