import React, { 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_POOL_LIST_TITLE = "View pools";

export const PoolWidgetConstants = {
  DEFAULT_RESULT_LIMIT,
  DEFAULT_VIEW_POOL_LIST_TITLE,
};

interface IProps {
  environment: Environment;
  viewPoolListTitle: string;
  inlineMode?: boolean;
  alwaysExpanded?: boolean;
  showFilterPanel?: boolean;
  width?: string;
  height?: string;
  columnList?: string | string[];
  columnNameList?: string | string[];
  pageSize?: number;
  chainId?: number;
  productId?: string;
  marketId?: string;
  poolIdList?: string[];
}

export function PoolWidget({
  viewPoolListTitle,
  inlineMode,
  alwaysExpanded,
  width,
  height,
  showFilterPanel,
  columnList,
  columnNameList,
  environment,
  pageSize,
  chainId,
  productId,
  marketId,
  poolIdList,
}: 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-pool-widget"
      title="Atomica pool widget"
      frameBorder="0"
      width={width}
      height={height}
      src={`${baseUrl}/pool-list-internal?showFilterPanel=${showFilterPanel
      }&columnList=${columnList ? columnList : ""
      }&columnNameList=${typeof(columnNameList) === 'object' ? columnNameList.join("|") : columnNameList ?? ""
      }&pageSize=${pageSize ?? ""
      }&chainId=${chainId ?? ""
      }&marketId=${marketId ?? ""
      }&product=${encodeURI(productId ?? "")
      }&poolIdList=${poolIdList ? poolIdList : ""
    }`}
    />
  </>;

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

  return <div>
    <div className="w-pool-widget__title">
      <a className={'link-button'} onClick={toggleDetails}>
        {viewPoolListTitle || DEFAULT_VIEW_POOL_LIST_TITLE}
      </a>
      {
        !alwaysExpanded && inlineMode && <div onClick={toggleDetails} className={`w-pool-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>;
}
