import React, { useEffect, useState } from 'react';
import { Environment, QueryService } from 'rm-sdk';

import "./styles.scss";
import { Web3Provider } from '@ethersproject/providers';
import { tryParseJSON } from '../../utils/commonUtils';
import { useDynamicEntityList } from './helper';
import { MarketQueryResult } from 'rm-sdk/build/query.service';
import { ActivateMarketProtectionWidget } from './ActivateMarketProtectionWidget';
import { Spinner } from '../../components/ui/Widget';
import { insertLinksAndSpinnersInString } from '../../utils/uiUtils';


const DEFAULT_RESULT_LIMIT = 1;

const DEFAULT_NO_ASSET_TITLE = "No asset to protect";
const DEFAULT_NO_PROTECTION_TITLE = "No markets found";
// const DEFAULT_ACTIVATE_PROTECTION_TITLE = 'From {rate}%/year on market  #{marketNo} "{marketEntity}"';
// const DEFAULT_VIEW_PROTECTION_TITLE = 'Active protection for {coverage} {coverageCurrency} on market #{marketNo} "{marketEntity}"';

export const ActivateProtectionWidgetConstants = {
  DEFAULT_RESULT_LIMIT,
  DEFAULT_NO_ASSET_TITLE,
  DEFAULT_NO_PROTECTION_TITLE,
//  DEFAULT_ACTIVATE_PROTECTION_TITLE,
//  DEFAULT_VIEW_PROTECTION_TITLE,
};

interface IProps {
  provider?: Web3Provider;
  defaultProtectionAmount?: string;
  marketId?: string;
  productId?: string;
  chainId?: number;
  entityList?: Array<{key: string; value: string;}> | string;
  environment?: Environment | string;

  frontendOperator?: string;
  referrer?: string;
  activateProtectionTitle?: string;
  viewProtectionTitle?: string;
  defaultDuration?: number;
  marketLimit?: number;
  noProtectionTitle?: string;
  noAssetTitle?: string;
  inlineMode?: boolean;

  alwaysExpanded?: boolean;
  showPolicyFilterPanel?: boolean;
  width?: string;
  height?: string;
  policyColumnList?: string | string[];
  policyColumnNameList?: string | string[];
  pageSize?: number;
  marketIdList?: string[];
  policyIdList?: string[];
}


export function ActivateProtectionWidget({
  provider,
  defaultProtectionAmount,
  marketId,
  productId,
  chainId,
  entityList,
  environment,
  frontendOperator,
  referrer,
  activateProtectionTitle,
  viewProtectionTitle,
  defaultDuration,
  marketLimit,
  noProtectionTitle,
  noAssetTitle,
  inlineMode,
  alwaysExpanded,
  showPolicyFilterPanel,
  width,
  height,
  policyColumnList,
  policyColumnNameList,
  pageSize,
  marketIdList,
  policyIdList,
}: IProps) {
  const [queryService] = useState(new QueryService());
  const [queryMarketResultList, setQueryMarketResultList] = useState<MarketQueryResult[]>();
  const entityListObject = typeof entityList === "string" ? tryParseJSON(entityList) : entityList;
  const entityValueList = useDynamicEntityList(entityListObject);

  useEffect(() => {
    setQueryMarketResultList(undefined);

    loadMarkets();
  }, [environment, chainId, marketId, productId, entityValueList]);

  async function loadMarkets() {
    const markets = await queryService.queryMarkets({
      marketIdList: marketId?.startsWith('0x') ? [marketId] : undefined,
      marketNoList: marketId && +marketId ? [+marketId] : undefined,
      productIdList: productId ? [productId] : undefined,
      envList: environment ? [environment] : undefined,
      chainIdList: chainId ? [+chainId] : undefined,
      entityList: entityValueList,
    });

    setQueryMarketResultList(markets.filter((_: any, i: number) => i < (marketLimit ?? DEFAULT_RESULT_LIMIT)));
  }

  const noAsset = !defaultProtectionAmount || (defaultProtectionAmount === "0");

  return <div>
    {noAsset && <div>{noAssetTitle || DEFAULT_NO_ASSET_TITLE}</div>}
    {!noAsset && queryMarketResultList == null && <Spinner />}
    {!noAsset && queryMarketResultList?.length === 0 && <div>{insertLinksAndSpinnersInString(noProtectionTitle || DEFAULT_NO_PROTECTION_TITLE, undefined, undefined)}</div>}
    {
      queryMarketResultList?.map((queryResult) =>
        <ActivateMarketProtectionWidget
          environment={queryResult.envId}
          marketId={queryResult.marketId}
          frontendOperator={frontendOperator}
          referrer={referrer}
          activateProtectionTitle={activateProtectionTitle}
          defaultProtectionAmount={defaultProtectionAmount}
          defaultDuration={defaultDuration}
          inlineMode={inlineMode}
          alwaysExpanded={alwaysExpanded}
          showPolicyFilterPanel={showPolicyFilterPanel}
          width={width}
          height={height}
          policyColumnList={policyColumnList}
          policyColumnNameList={policyColumnNameList}
          pageSize={pageSize}
          policyIdList={policyIdList}
          defaultTab={undefined}
        />
      )
    }
  </div>;
}
