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_POLICY_LIST_TITLE = "View policies";

export const PolicyListWidgetConstants = {
  DEFAULT_RESULT_LIMIT,
  DEFAULT_VIEW_POLICY_LIST_TITLE,
};

interface IProps {
  environment: Environment;
  viewPolicyListTitle: 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;
  policyIdList?: string[];
}

export function PolicyListWidget({
  viewPolicyListTitle,
  inlineMode,
  alwaysExpanded,
  width,
  height,
  showFilterPanel,
  columnList,
  columnNameList,
  environment,
  pageSize,
  chainId,
  productId,
  marketId,
  policyIdList,
}: IProps) {
  const [baseUrl, setBaseUrl] = useState("");

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

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

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

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