import { useState, useEffect, useCallback, useRef } from 'react';
import Label from '../Label';
import './MenuOption.scss';
import Chip from '../Chip';
import Icon from '../Icon';
import classNames from 'classnames';
import Tooltip from '../Tooltip';
import { createPortal } from 'react-dom';

export interface Option {
  label: string | React.ReactNode;
  value: Array<string> | string;
  chipText?: string;
  disable?: boolean;
}

interface OptionCardProps {
  isChipRequired?: boolean;
  options: Array<Option>;
  chipSize: 'small' | 'medium';
  onClick: (data?: any) => void;
  menuOptionPosition: {
    top: number;
    height: number;
    rightSpaceAvailable: number;
    bottom: number;
    fromBottom: number;
  };
  onBlurHandler: () => void;
  menuOptionRef: React.RefObject<HTMLDivElement>;
}

export interface MenuOptionProps {
  labelName?: string | React.ReactNode;
  /**
   * default icon to be display
   */
  iconName: string;
  options: Array<Option>;
  /**
   * if true displays chip
   */
  isChipRequired?: boolean;
  chipSize?: 'small' | 'medium';
  /**
   * tooltip title
   */
  tooltipTitle: string;
  placement: 'bottom' | 'left' | 'right' | 'top';
  onClick?: () => void;
  onOptionClick?: (data?: any) => void;
  disabled?: boolean;
}
interface OptionProps {
  option: Option;
  chipSize: 'small' | 'medium';
  onClick: (option: Option) => void;
}

const Option = ({ option, chipSize, onClick }: OptionProps) => {
  const [withWhiteBackground, setWithWhiteBackground] = useState(false);

  const onMouseEnter = () => {
    setWithWhiteBackground(true);
  };

  const onMouseLeave = () => {
    setWithWhiteBackground(false);
  };

  return (
    <div
      className={classNames('options', {
        'disable-option': option?.disable,
      })}
      onClick={() => !option?.disable && onClick(option)}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      <Label label={option?.label} className="options-label" color="info" />
      {option.chipText && (
        <span>
          <Chip
            label={option.chipText}
            size={chipSize}
            withWhiteBackground={withWhiteBackground}
          />
        </span>
      )}
    </div>
  );
};

const OptionCard = ({
  /**
   * if true displays chip
   */
  isChipRequired = false,
  options = [],
  chipSize = 'small',
  onClick = () => {},
  menuOptionPosition,
  menuOptionRef,
  onBlurHandler,
}: OptionCardProps) => {
  const [timerExpired, setTimerExpired] = useState(false);
  const [optionsHeight, setOptionHeight] = useState(0);

  const optionsRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const timer = setTimeout(() => {
      setTimerExpired(true);
    }, 5000);

    if (optionsRef?.current) {
      const rect = optionsRef?.current?.getBoundingClientRect();
      setOptionHeight(rect?.height);
    }
    return () => {
      clearTimeout(timer);
    };
  }, []);
  useEffect(() => {
    const handleOutsideClick = (event: MouseEvent) => {
      if (
        optionsRef.current &&
        menuOptionRef.current &&
        !optionsRef.current.contains(event?.target as Node) &&
        !menuOptionRef.current.contains(event?.target as Node)
      ) {
        onBlurHandler();
      }
    };
    document.addEventListener('click', handleOutsideClick, true);
    window.addEventListener('resize', () => {});
    return () => {
      document.removeEventListener('click', handleOutsideClick, true);
    };
  }, []);
  return createPortal(
    <div
      ref={optionsRef}
      style={
        menuOptionPosition.fromBottom > optionsHeight + 7
          ? {
              top: menuOptionPosition.bottom,
              right: menuOptionPosition.rightSpaceAvailable,
              width: 'max-content',
              zIndex: '1000000',
            }
          : {
              top: menuOptionPosition.top - optionsHeight - 5,
              right: menuOptionPosition.rightSpaceAvailable,
              width: 'max-content',
              zIndex: '1000000',
            }
      }
      className="storybook-option-card"
    >
      <div className="options-wrapper">
        {options && options.length > 0 ? (
          options.map((opt, index) => (
            <Option
              key={index}
              option={opt}
              chipSize={chipSize}
              onClick={onClick}
            />
          ))
        ) : (
          <div className="options">
            <Label
              label={timerExpired ? 'No Options' : 'Loading...'}
              className="options-label"
              color="info"
            />
          </div>
        )}
      </div>
    </div>,
    document.body
  );
};

const MenuOption = ({
  labelName,
  iconName,
  options = [],
  isChipRequired = false,
  chipSize = 'small',
  tooltipTitle = 'Tooltip-Title',
  placement = 'bottom',
  onClick = () => {},
  onOptionClick = () => {},
  disabled = false,
}: MenuOptionProps) => {
  const [isClicked, setIsClicked] = useState(false);
  const menuOptionRef = useRef<HTMLDivElement>(null);
  const [menuOptionPosition, setMenuOptionPosition] = useState({
    top: 0,
    rightSpaceAvailable: 0,
    height: 0,
    bottom: 0,
    fromBottom: 0,
  });

  const onBlurHandler = useCallback(() => {
    setIsClicked(false);
  }, []);
  const calculateDims = () => {
    if (menuOptionRef?.current) {
      const rect = menuOptionRef.current.getBoundingClientRect();

      setMenuOptionPosition({
        top: rect.top,
        height: rect.height,
        rightSpaceAvailable: document.body.clientWidth - rect.right,
        bottom: rect.bottom,
        fromBottom: window.innerHeight - rect.bottom,
      });
    }
  };
  const onIconClickHandler = (event: React.MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
    if (!isClicked) {
      calculateDims();
    }

    setIsClicked((prev) => !prev);
  };

  useEffect(() => {
    if (isClicked) {
      onClick();
    }
    const handleScroll = () => {
      setIsClicked(false);
    };
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', calculateDims);
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculateDims);
    };
  }, [isClicked]);

  const handleOptionClick = (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>
  ) => {
    onOptionClick(event);
    onBlurHandler();
  };

  return (
    <div ref={menuOptionRef} className="storybook-menu-option-container">
      <Tooltip title={tooltipTitle} placement={placement}>
        <div className="storybook-icon">
          <Icon
            disabled={disabled}
            onClick={onIconClickHandler}
            height={14}
            width={14}
            name={iconName}
            hoverEffect={true}
          />
          {typeof labelName === 'string' ? (
            <Label label={labelName} />
          ) : (
            labelName
          )}
        </div>
      </Tooltip>
      {isClicked && (
        <OptionCard
          options={options}
          isChipRequired={isChipRequired}
          chipSize={chipSize}
          onClick={handleOptionClick}
          menuOptionPosition={menuOptionPosition}
          onBlurHandler={onBlurHandler}
          menuOptionRef={menuOptionRef}
        />
      )}
    </div>
  );
};

export default MenuOption;
