/**
 * @Author: ??
 * @Date: ??
 */
import React, { useEffect, useState } from "react";
import { AdjustingMarginModalProps } from "./interface";
import { Modal, ModalProps } from "../../index";
import "./index.css";
import { Select } from "@atomintl/aui-next";
import { formatFloor, formatMoney, toDefaultNumber } from "@utils/FormatNumber";
import { calcLiquidationPrice, ESide } from "@utils/contractRules";
import { ArrowDown } from "@icons/ArrowDown";
import NumberInput from "@components/Input/NumberInput";
import { Form } from "@atomintl/aui-next";

const { Option } = Select;

export enum EMarginDirection {
  up = "1",
  down = "2"
}

interface MockFormValues {
  name: string;
  age: number;
}

/**
 * ### 引用方法
 * ```tsx
 * import { AdjustingMarginModal } from "@atomintl/exchange-ui";
 * ```
 */
export const AdjustingMarginModal: React.FC<AdjustingMarginModalProps & ModalProps> = props => {
  const {
    onConfirm,
    maxIncreaseMargin,
    posMargin,
    positionAmt,
    averagePosPrice,
    marginRatio,
    amtRate,
    takerRate,
    side,
    liquidationPriceScale,
    open
  } = props;
  const [type, setType] = useState<EMarginDirection>(EMarginDirection.up);
  const [liquidationPrice, setLiquidationPrice] = useState<number>();
  const [increaseMargin, setIncreaseMargin] = useState<string>("");
  const onOkCb = () => {
    onConfirm?.({
      type,
      increaseMargin
    });
  };

  useEffect(() => {
    if (open) {
      setType(EMarginDirection.up);
      setLiquidationPrice(0);
      setIncreaseMargin("");
    }
  }, [open]);

  const TinyBox = ({ label, valuePrefix, value }: { label: string; valuePrefix?: string; value: string | number }) => {
    return (
      <div className="flex items-center justify-between my-[6px] text-[14px]">
        <div className="text-[#3c3c4399]">{label}</div>
        <div className="flex items-center justify-end">
          <div className="text-[#3c3c4399] mr-[4px]">{valuePrefix}</div>
          <span className="text-black font-bold">{value}</span>
        </div>
      </div>
    );
  };
  const directionText = type == EMarginDirection.up ? "增加" : "减少";

  const onSelectChange = (v: EMarginDirection) => {
    setType(v);
    onIncreaseMarginChange("");
  };

  const onIncreaseMarginChange = (v: string | number) => {
    const n = type == EMarginDirection.up ? toDefaultNumber(v) : 0 - toDefaultNumber(v);
    setIncreaseMargin(String(v));
    const liquidationPrice = calcLiquidationPrice({
      posMargin: toDefaultNumber(posMargin),
      increaseMargin: n,
      positionAmt: toDefaultNumber(positionAmt),
      averagePosPrice: toDefaultNumber(averagePosPrice),
      marginRatio: toDefaultNumber(marginRatio),
      amtRate: toDefaultNumber(amtRate),
      takerRate: toDefaultNumber(takerRate),
      direction: side as ESide
    });
    const formattedLiquidationPrice = toDefaultNumber(liquidationPrice) >= 0 ? toDefaultNumber(liquidationPrice) : 0;
    setLiquidationPrice(formattedLiquidationPrice);
  };
  const onMarginChange = (v: string) => onIncreaseMarginChange(v);
  const onMaxIncreaseMargin = () =>
    onIncreaseMarginChange(type === EMarginDirection.up ? maxIncreaseMargin : posMargin);

  const { useForm } = Form;
  const [form] = useForm<MockFormValues>({ defaultValues: { name: "abc", age: 18 } });

  return (
    <>
      <Modal
        title="调整保证金"
        cancelText=""
        okText="确认"
        confirmConfig={{ color: "primary", className: "h-[48px]", size: "large" }}
        onOk={onOkCb}
        {...props}
      >
        <div>
          <TinyBox
            label={`总额(USDT)`}
            valuePrefix={`最大可${directionText}`}
            value={`${formatMoney(toDefaultNumber(maxIncreaseMargin))} USDT`}
          />
          <div
            className={`flex items-center justify-between bg-[#7676801e] rounded-[4px] h-[48px] py-[6px] pl-[12px] pr-[16px] mb-[12px]`}
          >
            <Select
              selectWidth={100}
              labelProps={{
                className: `labelStyles`
              }}
              icon={<ArrowDown />}
              iconProps={{
                className: `flex items-center justify-center p-0 m-0`,
                style: {
                  width: 7,
                  height: 4,
                  marginLeft: 8
                }
              }}
              value={type}
              label={"增加保证金"}
              style={{ background: "transparent", color: "#000", fontSize: 14, fontWeight: 500 }}
              onChange={onSelectChange}
            >
              <Option value={EMarginDirection.up}>{"增加保证金"}</Option>
              <Option value={EMarginDirection.down}>{"减少保证金"}</Option>
            </Select>
            <div className={`h-[20px] border-l border-solid border-[#3c3c432e] mx-[12px]`}></div>
            {/*<Form*/}
            {/*  classes={{ error: "error-cls", form: "form-cls", item: "item-cls" }}*/}
            {/*  form={form}*/}
            {/*  validateTrigger={"onBlur"}*/}
            {/*  onValuesChange={(values, fieldValue) => {*/}
            {/*    console.log("onValuesChange", values, fieldValue.age, fieldValue.name);*/}
            {/*  }}*/}
            {/*  onFinish={formValues => alert(JSON.stringify(formValues))}*/}
            {/*>*/}
            {/*  <Form.Item*/}
            {/*    name="name"*/}
            {/*    rules={{*/}
            {/*      required: { value: true, message: "name不能为空" },*/}
            {/*      maxLength: { value: 15, message: "字符长度必须小于等于15" },*/}
            {/*    }}*/}
            {/*  >*/}
            {/*    <input type="text"/>*/}
            {/*  </Form.Item>*/}
            {/*  /!*<Form.Item>*!/*/}
            {/*  /!*  <button type="submit">提交</button>*!/*/}
            {/*  /!*</Form.Item>*!/*/}
            {/*</Form>*/}
            {/*<button onClick={() => {*/}
            {/*  form.handleSubmit({})*/}
            {/*}}>提交</button>*/}

            <NumberInput
              variant="outlined"
              textAlign={"left"}
              className={`flex-1`}
              style={{ border: 0, padding: 0, background: "transparent" }}
              classes={{ inputRootContainer: `flex-1`, inputRoot: `paddingleft0` }}
              value={increaseMargin}
              onChange={onMarginChange}
              scale={2}
            />
            <div className={`w-[32px] text-[16px] text-blue cursor-pointer`} onClick={onMaxIncreaseMargin}>
              最大
            </div>
          </div>
          <TinyBox label={`当前仓位保证金(BTCUSDT 永续)`} value={`${formatMoney(toDefaultNumber(posMargin))} USDT`} />
          <TinyBox
            label={`最大可${directionText}`}
            value={`${formatMoney(toDefaultNumber(type === EMarginDirection.up ? maxIncreaseMargin : posMargin))} USDT`}
          />
          <TinyBox
            label={`调整后参考强平价`}
            value={`${formatMoney(
              formatFloor(toDefaultNumber(liquidationPrice), toDefaultNumber(liquidationPriceScale))
            )} USDT`}
          />
        </div>
      </Modal>
    </>
  );
};

AdjustingMarginModal.defaultProps = {};

export type { AdjustingMarginModalProps };
export default AdjustingMarginModal;
