import {useState, useEffect} from 'react';
import {
  Spinner,
} from '../../components/ui/Widget';
import { Environment } from 'rm-sdk/build/types';
import { Web3Provider } from '@ethersproject/providers';
import { QueryService } from 'rm-sdk/build';
import { MarketQueryResult } from 'rm-sdk/build/query.service';
import { ControlType, RMWidget } from '../RMWidget';
import { useDynamicEntityList } from './helper';
import { tryParseJSON } from 'rm-sdk/build/services/api.service';
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 ProtectionWidgetConstants = {
  DEFAULT_RESULT_LIMIT,
  DEFAULT_NO_ASSET_TITLE,
  DEFAULT_NO_PROTECTION_TITLE,
  DEFAULT_ACTIVATE_PROTECTION_TITLE,
  DEFAULT_VIEW_PROTECTION_TITLE,
};

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

  className?: string;
  frontendOperator?: string;
  referrer?: string;
  activateProtectionTitle?: string;
  viewProtectionTitle?: string;
  defaultDuration?: number;
  marketLimit?: number;
  noProtectionTitle?: string;
  noAssetTitle?: string;
  incomeApyRate?: string;
  controlType?: ControlType;
  inlineMode?: boolean;
}

export function ProtectionWidget({
  provider,
  protectionAmount,
  marketId,
  productId,
  chainId,
  entityList,
  environment,

  className,
  frontendOperator,
  referrer,
  activateProtectionTitle,
  viewProtectionTitle,
  defaultDuration,
  marketLimit = DEFAULT_RESULT_LIMIT,
  noProtectionTitle,
  noAssetTitle,
  incomeApyRate,
  controlType = 'website-link',
  inlineMode,
}: IProps) {
  const [queryService] = useState(new QueryService());
  const [marketList, setMarketList] = useState<MarketQueryResult[]>();
  const entityListObject = typeof entityList === "string" ? tryParseJSON(entityList) : entityList;
  const entityValueList = useDynamicEntityList(entityListObject);

  useEffect(() => {
    if (!protectionAmount || protectionAmount === "0") {
      return;
    }

    setMarketList(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,
    });

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

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

  return <div>
    {noAsset && <div>{noAssetTitle || DEFAULT_NO_ASSET_TITLE}</div>}
    {!noAsset && marketList == null && <Spinner />}
    {!noAsset && marketList?.length === 0 && <div>{insertLinksAndSpinnersInString(noProtectionTitle || DEFAULT_NO_PROTECTION_TITLE, undefined, undefined)}</div>}
    {
      marketList?.map((m, i) =>
      <RMWidget
        key={i}
        provider={provider}
        environment={m.envId}
        marketId={m.marketId}
        protectionAmount={protectionAmount}
        className={className}
        controlType={controlType}
        activateProtectionTitle={activateProtectionTitle || DEFAULT_ACTIVATE_PROTECTION_TITLE}
        viewProtectionTitle={viewProtectionTitle || DEFAULT_VIEW_PROTECTION_TITLE}
        frontendOperator={frontendOperator}
        referrer={referrer}
        defaultDuration={defaultDuration}
        incomeApyRate={incomeApyRate}
        inlineMode={inlineMode}
      />) || <></>
    }
   </div>;
}
