import React, { useEffect, useImperativeHandle, useRef, useState } from "react";
import { PositionDeliveryModalProps } from "./interface";
import Modal, { ModalProps } from "../Modal";
import { Select } from "@atomintl/aui-next";
import { NumberInput } from "@components/Input";
import { BottomTips, Hairline } from "@components/PositionDeliveryModal/Widgets";
import { Headers } from "./Widgets/Headers";
import { ArrowDown } from "@icons/ArrowDown";
import { DirEnum } from "@utils/contractRules";
import StartAdornment from "@components/PositionDeliveryModal/Widgets/StartAdornment";
import { endAdornmentSelector, numberInput, selector } from "./config/deliveryStyles";
import { priceTypes, units } from "@components/PositionDeliveryModal/config";
import { curry } from "ramda";
import "./index.css";
import ProfitTips, { TipsPropsRefProps } from "@components/PositionDeliveryModal/Widgets/ProfitTips";
import SaranWrap from "@components/PositionDeliveryModal/Widgets/SaranWrap";
import { toDefaultNumber } from "@utils/FormatNumber";

export type SelectorValueProps = { label: string; value: string } | undefined;
const { Option } = Select;
/**
 * ### 引用方法
 * ```tsx
 * import { PositionDeliveryModal } from "@atomintl/exchange-ui";
 * ```
 */
export const PositionDeliveryModal: React.FC<PositionDeliveryModalProps & ModalProps> = props => {
  const {
    onConfirm,
    symbol,
    side,
    level,
    avgEntryPrice,
    tickSizeScale,
    newestPrice,
    positionAmt,
    ctVal,
    ctValScale,
    costSizeScale,
    posMargin,
    initPxs,
    setInitPxs
  } = props;
  const [profitV, setProfitV] = useState<string>("");
  const [profitUnit, setProfitUnit] = useState<{ label: string; value: string }>(units[0]);
  const [profitType, setProfitType] = useState<{ label: string; value: string }>(priceTypes[0]);
  const [lossV, setLossV] = useState<string>("");
  const [lossUnit, setLossUnit] = useState<{ label: string; value: string }>(units[0]);
  const [lossType, setLossType] = useState<{ label: string; value: string }>(priceTypes[0]);
  const profitTipsRef = useRef<TipsPropsRefProps>();
  const lossTipsRef = useRef<TipsPropsRefProps>();
  const finder2Trigger = (arr: Array<any>, func: Function, kv: string) => {
    const o: SelectorValueProps = arr.find(x => x.value == kv);
    o && func(o);
  };
  const curriedFinder2Trigger = curry(finder2Trigger);
  const onOkCb = () => {
    onConfirm?.({
      profitV,
      profitUnit,
      profitType,
      profitStrikePrice: profitTipsRef.current?.getStrikePrice(),
      lossV,
      lossUnit,
      lossType,
      lossStrikePrice: lossTipsRef.current?.getStrikePrice()
    });
  };

  useEffect(() => setProfitV(""), [profitUnit]);
  useEffect(() => setLossV(""), [lossUnit]);

  useEffect(() => {
    if (!!props?.open) {
      setProfitV("");
      setProfitUnit(units[0]);
      setProfitType(priceTypes[0]);
      setLossV("");
      setLossUnit(units[0]);
      setLossType(priceTypes[0]);
    }
  }, [props?.open]);

  useImperativeHandle(props?.onRef, () => ({}));

  return (
    <>
      <Modal
        title="仓位止盈止损"
        cancelText=""
        okText="确认"
        confirmConfig={{ color: "primary", className: "h-[48px]", size: "large" }}
        onOk={onOkCb}
        {...props}
      >
        <div className={`text-[14px]`}>
          <Headers
            symbol={symbol}
            side={side}
            level={level}
            avgEntryPrice={avgEntryPrice}
            newestPrice={newestPrice}
            scale={tickSizeScale}
          />
          <div className={`flex justify-between items-center mt-[20px]`}>
            {!!initPxs?.tpTriggerPx ? (
              <SaranWrap
                side={side}
                costSizeScale={costSizeScale}
                dir={DirEnum.UP}
                initPxs={initPxs}
                setInitPxs={setInitPxs}
              />
            ) : (
              <>
                <NumberInput
                  scale={tickSizeScale}
                  value={profitV}
                  onChange={setProfitV}
                  variant="outlined"
                  className={`py-[3px] pl-[12px] rounded-[4px] flex items-center justify-between w-[364px]`}
                  style={numberInput.style}
                  classes={numberInput.classes}
                  startAdornment={<StartAdornment dir={DirEnum.UP} showTooltip={profitUnit.value === "2"} />}
                  endAdornment={
                    <Select
                      labelProps={endAdornmentSelector.labelProps}
                      icon={<ArrowDown />}
                      iconProps={endAdornmentSelector.iconProps}
                      placement={`right`}
                      value={profitUnit.value}
                      label={profitUnit.label}
                      style={endAdornmentSelector.style}
                      onChange={curriedFinder2Trigger(units, setProfitUnit)}
                      optionWidth={endAdornmentSelector.optionWidth}
                    >
                      {units.map(_item => (
                        <Option
                          key={_item.value}
                          value={_item.value}
                          className={`text-[14px] pt-[9px] pb-[10px] px-[16px]`}
                        >
                          {_item.label}
                        </Option>
                      ))}
                    </Select>
                  }
                />
                <Select
                  labelProps={selector.labelProps}
                  value={profitType.value}
                  label={profitType.label}
                  className={`my-select`}
                  onChange={curriedFinder2Trigger(priceTypes, setProfitType)}
                >
                  {priceTypes.map(_item => (
                    <Option
                      key={_item.value}
                      value={_item.value}
                      className={`text-[14px] pt-[9px] pb-[10px] px-[16px]`}
                    >
                      {_item.label}
                    </Option>
                  ))}
                </Select>
              </>
            )}
          </div>
          <ProfitTips
            onRef={profitTipsRef}
            initProfitValue={toDefaultNumber(initPxs?.tpTriggerPx)}
            profitV={profitV}
            initLossValue={toDefaultNumber(initPxs?.slTriggerPx)}
            lossV={lossV}
            tickSizeScale={tickSizeScale}
            avgEntryPrice={avgEntryPrice}
            positionAmt={positionAmt}
            ctVal={ctVal}
            ctValScale={ctValScale}
            costSizeScale={costSizeScale}
            profitUnit={profitUnit}
            lossUnit={lossUnit}
            posMargin={posMargin}
            side={side}
            dir={DirEnum.UP}
            typeLabel={profitType.label}
          />
          <Hairline />
          <div className={`flex justify-between items-center mt-[20px]`}>
            {!!initPxs?.slTriggerPx ? (
              <SaranWrap
                side={side}
                costSizeScale={costSizeScale}
                dir={DirEnum.DOWN}
                initPxs={initPxs}
                setInitPxs={setInitPxs}
              />
            ) : (
              <>
                <NumberInput
                  scale={tickSizeScale}
                  value={lossV}
                  allowNegative
                  onChange={v => {
                    // if (lossUnit.value === '2' && toDefaultNumber(v) > 0){
                    //   v = new Decimal(toDefaultNumber(v)).mul(-1).toString();
                    // }
                    setLossV(v);
                  }}
                  variant="outlined"
                  className={`py-[3px] pl-[12px] rounded-[4px] flex items-center justify-between w-[364px]`}
                  style={numberInput.style}
                  classes={numberInput.classes}
                  startAdornment={<StartAdornment dir={DirEnum.DOWN} showTooltip={lossUnit.value === "2"} />}
                  endAdornment={
                    <Select
                      labelProps={endAdornmentSelector.labelProps}
                      icon={<ArrowDown />}
                      iconProps={endAdornmentSelector.iconProps}
                      placement={`right`}
                      value={lossUnit.value}
                      label={lossUnit.label}
                      style={endAdornmentSelector.style}
                      onChange={curriedFinder2Trigger(units, setLossUnit)}
                      optionWidth={endAdornmentSelector.optionWidth}
                    >
                      {units.map(_item => (
                        <Option
                          key={_item.value}
                          value={_item.value}
                          className={`text-[14px] pt-[9px] pb-[10px] px-[16px]`}
                        >
                          {_item.label}
                        </Option>
                      ))}
                    </Select>
                  }
                />
                <Select
                  labelProps={selector.labelProps}
                  value={lossType.value}
                  label={lossType.label}
                  className={`my-select`}
                  onChange={curriedFinder2Trigger(priceTypes, setLossType)}
                >
                  {priceTypes.map(_item => (
                    <Option
                      key={_item.value}
                      value={_item.value}
                      className={`text-[14px] pt-[9px] pb-[10px] px-[16px]`}
                    >
                      {_item.label}
                    </Option>
                  ))}
                </Select>
              </>
            )}
          </div>
          <ProfitTips
            onRef={lossTipsRef}
            initProfitValue={toDefaultNumber(initPxs?.tpTriggerPx)}
            profitV={profitV}
            initLossValue={toDefaultNumber(initPxs?.slTriggerPx)}
            lossV={lossV}
            tickSizeScale={tickSizeScale}
            avgEntryPrice={avgEntryPrice}
            positionAmt={positionAmt}
            ctVal={ctVal}
            ctValScale={ctValScale}
            costSizeScale={costSizeScale}
            profitUnit={profitUnit}
            lossUnit={lossUnit}
            posMargin={posMargin}
            side={side}
            dir={DirEnum.DOWN}
            typeLabel={lossType.label}
          />
          <BottomTips />
        </div>
      </Modal>
    </>
  );
};

PositionDeliveryModal.defaultProps = {};

export type { PositionDeliveryModalProps, priceTypes, units, TipsPropsRefProps };
export default PositionDeliveryModal;
