import React, { useEffect, useState } from 'react';
import { Environment, SDK } from 'rm-sdk';
import { WidgetContentWrapper } from '../WidgetContentWrapper';

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("");

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

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

  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 : ""
    }`}
    />
  </>;

  return (<WidgetContentWrapper
    title={viewPoolListTitle || DEFAULT_VIEW_POOL_LIST_TITLE}
    content={Content}
    inlineMode={inlineMode}
    alwaysExpanded={alwaysExpanded}
  />);
}
