import BigNumber from "bignumber.js";
import { useEffect, useState } from "react";
import { RateService } from "rm-sdk/build/";
import { Token } from "rm-sdk/build/interfaces/token.interface";
import { LabelText } from "../../components/ui/Widget";
import { toSuffixFormat } from "../../utils/configureFormats";
import { CurrencyInput } from "../../components/CurrencyInput";
import { RangeInput } from "../../components/RangeInput";

const DEFAULT_MIN_DURATION = 2
const DEFAULT_MAX_DURATION = 90

interface IProps {
  capitalTokenInfo?: Token
  premiumTokenInfo?: Token
  topUpValue?: BigNumber
  desiredCover: string
  handleDesiredCoverChanged: (value: string) => boolean
  handleTopUpValueChanged: (value: string) => boolean
  handleDurationChanged: (value: number) => boolean
  minDeposit?: BigNumber
  rate?: string
  monthPrice?: BigNumber
  duration: number
  referralBonus?: BigNumber
  totalDeposit: BigNumber | undefined
  minDuration?: number
  maxDuration?: number
}

function renderDuration(durationInDays: number): string {
  if (durationInDays == null) {
    return "-"
  }

  if (durationInDays / 365 / 10 > 1) {
    return "10+ years"
  }

  if (durationInDays / 365 >= 1) {
    const years = Math.floor(durationInDays / 365)

    const remainingDays = durationInDays % 365

    return `${years} year${years > 1 ? "s" : ""}${
      remainingDays > 0 ? ` and ${renderDuration(remainingDays)}` : ""
    }`
  }

  const days = Math.floor(durationInDays)
  return `${days} day${days > 1 ? "s" : ""}`
}

const rateService = new RateService()

export function CustomActivateProtectionView({
  minDuration = DEFAULT_MIN_DURATION,
  maxDuration = DEFAULT_MAX_DURATION,
  ...props
}: IProps) {
  const [coverIsEditing, setCoverIsEditing] = useState(true)
  const [depositIsEditing, setDepositIsEditing] = useState(true)
  const [capitalTokenPriceUsd, setCapitalTokenPriceUsd] = useState(0)
  const [premiumTokenPriceUsd, setPremiumTokenPriceUsd] = useState(0)

  const setTokenPrice = async (
    tokenInfo: Token | undefined,
    setter: React.Dispatch<React.SetStateAction<number>>
  ) => {
    if (tokenInfo?.address) {
      setter(await rateService.getPrice(tokenInfo.symbol, tokenInfo.name))
    }
  }

  useEffect(() => {
    setTokenPrice(props.capitalTokenInfo, setCapitalTokenPriceUsd)
  }, [props.capitalTokenInfo?.address])

  useEffect(() => {
    setTokenPrice(props.premiumTokenInfo, setPremiumTokenPriceUsd)
  }, [props.premiumTokenInfo?.address])

  const rangeDuration =
    props.duration > maxDuration
      ? maxDuration
      : props.duration < minDuration
      ? minDuration
      : Math.round(props.duration)

  return (
    <>
      {!coverIsEditing && (
        <LabelText>
          <div>
            Desired loan amount{" "}
            <a
              onClick={() => {
                setCoverIsEditing(true)
                setDepositIsEditing(false)
              }}
            >
              (edit)
            </a>
          </div>{" "}
          {(props.capitalTokenInfo && (
            <div>
              {props.desiredCover} {props.capitalTokenInfo.symbol}
            </div>
          )) ||
            "-"}
        </LabelText>
      )}
      {coverIsEditing && (
        <LabelText>
          <CurrencyInput
            currencyLogo={props.capitalTokenInfo?.logoURI}
            subLabels={[
              props.capitalTokenInfo?.symbol || "",
              (props.desiredCover &&
                capitalTokenPriceUsd &&
                `($${new BigNumber(props.desiredCover)
                  .times(capitalTokenPriceUsd)
                  .toFixed(2)})`) ||
                "",
            ]}
            value={props.desiredCover}
            onChange={props.handleDesiredCoverChanged}
            label={
              <div>
                Desired loan amount{" "}
                <a onClick={() => setCoverIsEditing(false)}>(close)</a>
              </div>
            }
            placeholder="e.g. 10 000.00"
          />
        </LabelText>
      )}
      <LabelText>
        <RangeInput
          label="Desired Duration of a Loan Auction (where lenders compete for the right to lend to you and submit their best bids)"
          maxLabel={`${renderDuration(maxDuration)} (max.)`}
          minLabel={`${renderDuration(minDuration)} (min.)`}
          min={minDuration}
          max={maxDuration}
          disabled={!Boolean(props.desiredCover)}
          value={rangeDuration}
          onChange={props.handleDurationChanged}
          valueLabel={renderDuration(props.duration)}
        />
      </LabelText>
      {!depositIsEditing && (
        <LabelText>
          <div>
            Loan Promotion Budget (pays interest to lenders during loan auction){" "}
            <a
              onClick={() => {
                setCoverIsEditing(false)
                setDepositIsEditing(true)
              }}
            >
              (edit)
            </a>
          </div>{" "}
          {(props.topUpValue && (
            <div>
              {props.topUpValue.toFixed(2, BigNumber.ROUND_UP)}{" "}
              {props.premiumTokenInfo?.symbol}
            </div>
          )) ||
            "-"}
        </LabelText>
      )}
      {depositIsEditing && (
        <LabelText>
          <CurrencyInput
            currencyLogo={props.premiumTokenInfo?.logoURI}
            subLabels={[
              props.premiumTokenInfo?.symbol || "",
              (props.topUpValue &&
                premiumTokenPriceUsd &&
                `($${new BigNumber(props.topUpValue)
                  .times(premiumTokenPriceUsd)
                  .toFixed(2)})`) ||
                "",
            ]}
            value={
              props.topUpValue?.toFixed(
                props.premiumTokenInfo?.decimals ?? 2,
                BigNumber.ROUND_UP
              ) || ""
            }
            onChange={props.handleTopUpValueChanged}
            label={
              <div>
                Loan Promotion Budget (pays interest to lenders during loan
                auction)
                <a onClick={() => setDepositIsEditing(false)}>(close)</a>
              </div>
            }
            placeholder="e.g. 10 000.00"
          />
        </LabelText>
      )}
      <LabelText valueColor="gray">
        <div>Maximum APR</div>{" "}
        <div>{(props.rate && `${props.rate}%`) || "-"}</div>
      </LabelText>
      <LabelText boldLabel boldValue>
        <div>Total</div>{" "}
        <div className="label-value">
          {(props.totalDeposit &&
            props.premiumTokenInfo &&
            `~${toSuffixFormat(props.totalDeposit, 2, BigNumber.ROUND_UP)} ${
              props.premiumTokenInfo.symbol
            }`) ||
            "-"}
        </div>
      </LabelText>
    </>
  )
}
