import { AdjustingLeverModal } from "../../../index";
import IconCom from "@icons/IconCom";
import { Edit } from "@icons/Edit";
import * as React from "react";
import { FC, useCallback, useEffect, useRef, useState } from "react";
import { formatFloor, toDefaultNumber } from "@utils/FormatNumber";
import {
  AdjustingLeverModalConfirmProps,
  AdjustingLeverModalRefFuncProps
} from "@components/AdjustingLeverModal/interface";
import { MarginTypeEnum, TradeTypeEnum } from "@shared/types";
import { usePost } from "@utils/request";
import { APINameEnum } from "@utils/request/ApiNameEnum";

export interface PositionColumnsLeverageProps {
  value: string | number;
  marginType: MarginTypeEnum;
  tradeType: TradeTypeEnum;
  symbol: string;
  pair: any;
}
export const PositionColumnsLeverage: FC<PositionColumnsLeverageProps> = props => {
  const { value, marginType, tradeType, symbol, pair } = props;
  const adjustingLeverModalRef = useRef<AdjustingLeverModalRefFuncProps>();

  const [open, setOpen] = useState(false);
  const onClose = useCallback(() => setOpen(false), []);
  const [leverage, setLeverage] = useState<number | string>(value);

  const openAdjustingLeverModal = () => {
    setOpen(true);
  };

  const [leverMutation, { data }] = usePost(APINameEnum.LEVERAGE);

  useEffect(() => {
    if (data) onClose();
  }, [data]);

  const onConfirm = (o: AdjustingLeverModalConfirmProps) => {
    setLeverage(toDefaultNumber(o.lever));
    leverMutation({
      tradeType,
      symbol,
      leverage,
      marginType
    });
  };

  return (
    <>
      <AdjustingLeverModal
        onRef={adjustingLeverModalRef}
        initMarginType={marginType}
        defaultLever={toDefaultNumber(value)}
        open={open}
        onClose={onClose}
        onConfirm={onConfirm}
        disabledCross={marginType === MarginTypeEnum.Isolated}
        disabledIsolated={marginType === MarginTypeEnum.Cross}
        tradeType={tradeType}
        symbol={symbol}
      />
      <div className="flex items-center">
        <span className={`mr-[4px]`}>{`${formatFloor(value, pair?.leverageScale)}X`}</span>
        <IconCom onClick={openAdjustingLeverModal}>
          <Edit />
        </IconCom>
      </div>
    </>
  );
};
