import { useEffect, useState } from 'react';
import { Environment, SDK } from 'rm-sdk';
import { ArrowDownIcon } from '../../components/ArrowDownIcon';
import Modal from '../../components/Modal';

import "./styles.scss";

const DEFAULT_RESULT_LIMIT = 10;
const DEFAULT_VIEW_MARKET_LIST_TITLE = "View markets";

export const MarketWidgetConstants = {
  DEFAULT_RESULT_LIMIT,
  DEFAULT_VIEW_MARKET_LIST_TITLE,
};

interface IProps {
  environment: Environment;
  viewMarketListTitle: string;

  inlineMode?: boolean;
  alwaysExpanded?: boolean;
  showFilterPanel?: boolean;
  width?: string;
  height?: string;
  columnList?: string | string[];
  columnNameList?: string | string[];
  coverInputTitle?: string;
  pageSize?: number;
  chainId?: number;
  productId?: string;
  marketIdList?: string[];
}

export function MarketWidget({
  viewMarketListTitle,
  inlineMode,
  alwaysExpanded,
  width,
  height,
  showFilterPanel,
  columnList,
  columnNameList,
  coverInputTitle,
  environment,
  pageSize,
  chainId,
  productId,
  marketIdList,
}: IProps) {
  const [baseUrl, setBaseUrl] = useState("");
  const [isOpen, setOpen] = useState(!!inlineMode || false);

  useEffect(() => {
    const sdk = new SDK(environment);

    setBaseUrl(sdk.envConfig?.uiUrl || "");
  }, [environment]);

  const toggleDetails = () => {
    setOpen(!isOpen);
  };
  const Content = <>
    <iframe
      className="w-market-widget"
      title="Atomica market widget"
      frameBorder="0"
      width={width}
      height={height}
      src={`${baseUrl}/market-list-internal?showFilterPanel=${showFilterPanel
      }&columnList=${columnList ? columnList : ""
      }&columnNameList=${typeof(columnNameList) === 'object' ? columnNameList.join("|") : columnNameList ?? ""
      }&pageSize=${pageSize ?? ""
      }&chainId=${chainId ?? ""
      }&product=${encodeURI(productId ?? "")
      }&marketIdList=${marketIdList ? marketIdList : ""
      }&coverInputTitle=${coverInputTitle ?? ""
      }`}
    />
  </>;

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

  return <div>
    <div className="w-market-widget__title">
      <a className={'link-button'} onClick={toggleDetails}>
        {viewMarketListTitle || DEFAULT_VIEW_MARKET_LIST_TITLE}
      </a>
      {
        !alwaysExpanded && inlineMode && <div onClick={toggleDetails} className={`w-market-widget__arrow-span ${(isOpen && "expanded") || ""}`}>
          <ArrowDownIcon />
        </div>
      }
    </div>

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

    {!inlineMode && (isOpen || alwaysExpanded) &&
      <Modal isOpen={!!isOpen || !!alwaysExpanded}
        onBackgroundClick={closePopUp}
        onCloseClick={closePopUp}
        onEscPressed={closePopUp}
        width="90%"
        height="auto"
      >
        {Content}
      </Modal>
    }
  </div>;
}
