import React, { ReactElement, useState } from 'react';
import { ArrowDownIcon } from '../../components/ArrowDownIcon';
import Modal from '../../components/Modal';

import "./styles.scss";

interface IProps {
  title?: string;
  inlineMode?: boolean;
  alwaysExpanded?: boolean;
  width?: string;
  height?: string;
  content: ReactElement,
}

export function WidgetContentWrapper({
  title,
  inlineMode,
  alwaysExpanded,
  content,
  width = "90%",
  height = "auto",
}: IProps) {
  const [isOpen, setOpen] = useState(!!inlineMode || false);

  const toggleDetails = () => {
    setOpen(!isOpen);
  };

  const closePopUp = (e: any) => {
    if (e.target === e.currentTarget) {
      setOpen(false);
    }
  };

  return <div className="w-widget-content-wrapper">
    <div className="w-widget-content-wrapper__title">
      <a className={'link-button'} onClick={toggleDetails}>
        {title}
      </a>
      {
        !alwaysExpanded && inlineMode && <div onClick={toggleDetails} className={`w-widget-content-wrapper__arrow-span ${(isOpen && "expanded") || ""}`}>
          <ArrowDownIcon />
        </div>
      }
    </div>

    {
      (alwaysExpanded || isOpen) && inlineMode &&
      <>
        {content}
      </>
    }

    {!inlineMode && (isOpen || alwaysExpanded) &&
      <Modal isOpen={!!isOpen}
        onBackgroundClick={closePopUp}
        onCloseClick={closePopUp}
        onEscPressed={closePopUp}
        width={width}
        height={height}
      >
        {content}
      </Modal>
    }
  </div>;
}
