import { 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_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[];
  forceUiMode?: "mobile" | "desktop";
}

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

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

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

  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 ?? ""
      }${forceUiMode ? `&forceUIMode=${forceUiMode}` : ""}`}
    />
  </>;

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