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

const MIN_DURATION = 30;
const MAX_DURATION = 365;

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;
}

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);

    return `${years} year${years > 1 ? "s" : ""}`;
  }

  // if (durationInDays / 30 >= 1) {
  //   const days = ""; //durationInDays % 30 ? `${durationInDays % 30} day(s)` : "";
  //   const months = Math.floor(durationInDays / 30);

  //   return `${months} month${months > 1 ? "s" : ""} ${days}`;
  // }

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

const rateService = new RateService();

export function ActivateProtectionView(props: IProps) {
  const [coverIsEditing, setCoverIsEditing] = useState(false);
  const [depositIsEditing, setDepositIsEditing] = useState(false);
  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 > MAX_DURATION
    ? MAX_DURATION
    : props.duration < MIN_DURATION
    ? MIN_DURATION
    : Math.round(props.duration);

  return (<>
    {!coverIsEditing &&
      <LabelText>
        <div>Desired cover 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 cover amount <a onClick={() => setCoverIsEditing(false)}>(close)</a></div>}
            placeholder="e.g. 10 000.00"
          />
      </LabelText>
    }
    <LabelText>
      <RangeInput
        label="Estimated Duration"
        maxLabel={`${MAX_DURATION} days (max.)`}
        minLabel={`${MIN_DURATION} days (min.)`}
        min={MIN_DURATION}
        max={MAX_DURATION}
        disabled={!Boolean(props.desiredCover)}
        value={rangeDuration}
        onChange={props.handleDurationChanged}
        valueLabel={renderDuration(props.duration)}
      />
    </LabelText>
    {!depositIsEditing &&
      <LabelText><div>Top-up  <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>Top-up <a onClick={() => setDepositIsEditing(false)}>(close)</a></div>}
            placeholder="e.g. 10 000.00"
          />
      </LabelText>
    }
    <LabelText valueColor='gray'><div>Security deposit</div> <div>{(props.minDeposit && toSuffixFormat(props.minDeposit, 2, BigNumber.ROUND_UP)) || "-"} {props.premiumTokenInfo && `${props.premiumTokenInfo.symbol}`}</div></LabelText>
    {
      props.referralBonus && !props.referralBonus.isZero() &&
      <LabelText valueColor='limeGreen'><div>Referral Bonus</div> <div>-{toSuffixFormat(props.referralBonus, 2, BigNumber.ROUND_UP)} {props.premiumTokenInfo && `${props.premiumTokenInfo.symbol}`}</div></LabelText>
    }
    <LabelText valueColor='gray'><div>Estimated cost, per month</div> <div>{props.monthPrice ? `~${toSuffixFormat(props.monthPrice, 2, BigNumber.ROUND_UP)}` : "-"} {props.premiumTokenInfo && `${props.premiumTokenInfo.symbol}`}</div></LabelText>
    <LabelText valueColor='gray'><div>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>
  </>);

}