import { calcPreProfit, calcStrikePriceByReturnRate, DirEnum, ESide, getValueByContr } from "@utils/contractRules";
import { formatFloor, formatMoney, toDefaultNumber } from "@utils/FormatNumber";
import React, { FC, useImperativeHandle } from "react";

export interface TipsPropsRefProps {
  getStrikePrice: () => string;
}
export interface ProfitTipsProps {
  initProfitValue?: string | number;
  profitV: string;
  initLossValue?: string | number;
  lossV: string;
  tickSizeScale: number;
  avgEntryPrice: string | number;
  positionAmt: string | number;
  ctVal: string;
  ctValScale: number;
  costSizeScale: number;
  profitUnit: { label: string; value: string };
  lossUnit: { label: string; value: string };
  posMargin: string | number;
  side: ESide;
  dir: DirEnum;
  typeLabel: string;
  onRef?: React.Ref<TipsPropsRefProps | undefined>;
}
const ProfitTips: FC<ProfitTipsProps> = props => {
  const {
    initProfitValue,
    profitV,
    initLossValue,
    lossV,
    tickSizeScale,
    avgEntryPrice,
    positionAmt,
    ctVal,
    ctValScale,
    costSizeScale,
    profitUnit,
    lossUnit,
    posMargin,
    side,
    dir,
    typeLabel,
    onRef
  } = props;
  const isUp = dir === DirEnum.UP;
  const realStrikePrice = (v: string | number, unit: { label: string; value: string }) => {
    return unit.value === "2"
      ? calcStrikePriceByReturnRate({
          //切换回报率计算触发价
          returnRate: v,
          posMargin,
          avgEntryPrice,
          side,
          dir
        })
      : v;
  };
  const strikePrice = formatFloor(
    isUp ? realStrikePrice(initProfitValue || profitV, profitUnit) : realStrikePrice(initLossValue || lossV, lossUnit),
    tickSizeScale
  );
  const pr = calcPreProfit({
    strikePrice,
    avgEntryPrice: toDefaultNumber(avgEntryPrice),
    amt: getValueByContr({
      value: toDefaultNumber(positionAmt),
      multiplier: toDefaultNumber(ctVal),
      scale: ctValScale
    }),
    side,
    dir
  });
  const isPrEquals2Zero = pr === "--" || toDefaultNumber(pr) <= 0;
  const prDoodles = isPrEquals2Zero ? `text-derive-11` : isUp ? "text-green" : "text-red";
  const formattedPr = isPrEquals2Zero ? "--" : `${isUp ? "" : "-"}${formatMoney(formatFloor(pr, costSizeScale))}`;

  const getStrikePrice = () => {
    return strikePrice;
  };
  useImperativeHandle(onRef, () => ({ getStrikePrice }));

  return (
    <div className={`mt-[10px] text-derive-11`}>
      {`当`}
      <span className={`text-black font-medium`}>
        {typeLabel}
        {`价格`}
      </span>
      {`到达`}
      <span className={`text-black font-medium`}>{formatMoney(strikePrice)}</span>
      {`时，将会触发市价止盈委托平仓当前仓位。预计盈亏为`}
      <span className={`ml-[6px] font-medium ${prDoodles}`}>
        {formattedPr} {`USDT`}
      </span>
    </div>
  );
};

export default ProfitTips;
