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_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("");
  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-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 ?? ""
      }&product=${encodeURI(productId ?? "")
      }&policyIdList=${policyIdList ? policyIdList : ""
    }`}
    />
  </>;

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

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