import {useState, useEffect, useCallback} from "react";
import {Web3Provider} from "@ethersproject/providers";
import {QueryService} from "rm-sdk/build";
import {Environment} from "rm-sdk/build/types";
import {MarketQueryResult} from "rm-sdk/build/query.service";
import {Spinner} from "../../components/ui/Widget";
import {CustomRMWidget} from "./CustonRmWidget";
import { ContractReceipt } from "ethers";

const DEFAULT_NO_MARKET_TITLE = "Market not found"

export const RequestLoanWidgetConstants = {
  DEFAULT_NO_MARKET_TITLE,
};
interface IProps {
  desiredLoanAmount?: string
  provider: Web3Provider
  marketId: string
  chainId?: number
  environment?: Environment | string
  className?: string
  frontendOperator?: string
  referrer?: string
  defaultDuration?: number
  inlineMode?: boolean
  noMarketTitle?: string
  minDuration?: number
  maxDuration?: number
  hideLogo?: boolean
  onRequestSuccess?: (loanId: string, receipt: ContractReceipt) => void
}

export function RequestLoanWidget({
  desiredLoanAmount,
  provider,
  marketId,
  chainId,
  environment,
  noMarketTitle = DEFAULT_NO_MARKET_TITLE,
  className,
  frontendOperator,
  referrer,
  defaultDuration,
  minDuration,
  maxDuration,
  hideLogo = false,
  onRequestSuccess
}: IProps) {
  const [queryService] = useState(new QueryService())
  const [market, setMarket] = useState<MarketQueryResult | null>()

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

      if (markets.length) {
        setMarket(markets.at(0))
      } else {
        setMarket(null)
      }
    },
    [marketId, environment, chainId]
  )

  useEffect(() => {
    loadMarkets()
  }, [loadMarkets])

  return (
    <div>
      {market === undefined && <Spinner />}
      {market === null && <div>{noMarketTitle || DEFAULT_NO_MARKET_TITLE}</div>}
      {!!market && (
        <CustomRMWidget
          provider={provider}
          environment={market.envId}
          marketId={market.marketId}
          desiredLoanAmount={desiredLoanAmount}
          className={className}
          frontendOperator={frontendOperator}
          referrer={referrer}
          defaultDuration={defaultDuration}
          minDuration={minDuration}
          maxDuration={maxDuration}
          hideLogo={hideLogo}
          onRequestSuccess={onRequestSuccess}
        />
      )}
    </div>
  )
}
