import "./style/TradePanel.scss";

import 'sbx-react-form/libs/assets/styles/styles.scss';

import React, {Component} from "react";
import {Provider} from 'sbx-react-core';
import Form, {Fields} from 'sbx-react-form';


import classNames from "classnames";
import {getAssetSpreadInUserCurrency, getAssetSpread, getAssetSpreadInPoints} from "libs/Assets";
import {
    getOrderRequireMargin,
    orderIsBuy,
    orderIsActive,
    getPipsForVolume,
    getOrderSwap,
    getMultiplier,
    getPendingCmd,
    orderIsValid,
    getOrderType,
    getOrderCommission,
    getCurrencySymbol
} from "libs/Orders";

import {validatePrice} from "helpers/Validate";
import {calcResidual} from "helpers/Math";
import TpSlForm from "./TpSlForm";
import {openOrder, modifyOrder} from "actions/Orders";
import InputStep from "components/InputStep";
import Lang from "components/Language";

@Provider({
    asset: props => ['assets', props.order.symbol],
    quote: props => ['feed', props.order.symbol],
    user: ['profile', 'accounts'],
    settings: ['settings'],
})

export default class TradePanel extends Component {
    static defaultProps = {
        formType: "open"
    };
    stops = {
        sl: this.props.order.sl || 0,
        tp: this.props.order.tp || 0
    };

    state = {
        disabled: false,
        expirationShow: false
    };

    constructor(props) {
        super(props);
        const {formType, order, asset: {digits, stops_level}, quote: {ask, bid}} = props;
        const {cmd, open_price, sl, tp, volume} = order;
        let initialState = {};
        switch (formType) {
            case "open":
                initialState.activationPrice = orderIsBuy(cmd) ? (ask - stops_level / 10 ** digits).toFixed(digits) : (bid - stops_level / 10 ** digits).toFixed(digits);
                initialState.slIsEnable = false;
                initialState.tpIsEnable = false;
                break;
            case "modify":
                initialState.activationPrice = !orderIsActive(cmd) ? open_price : 0;
                initialState.slIsEnable = !!sl;
                initialState.tpIsEnable = !!tp;
                break;
        }
        initialState.volume = volume;
        initialState.cmd = cmd;
        if(order.expiration){
            initialState.expirationShow = true
        }
        this.state = initialState;
    }

    onChangeVolume = value => {
        this.setState({
            volume: value
        })
    };

    onInputActivationPrice = e => {
        const {value} = e.target;
        const {cmd} = this.props.order;
        const {ask, bid} = this.props.quote;
        const quote = orderIsBuy(cmd) ? ask : bid;
        let newCmd;
        if (validatePrice(value)) {
            this.setState({
                activationPrice: value
            }, () => {
                if (cmd === 1 && this.state.activationPrice > quote) {
                    newCmd = 13
                }
                if (cmd === 1 && this.state.activationPrice < quote) {
                    newCmd = 5
                }
                if (cmd === 0 && this.state.activationPrice > quote) {
                    newCmd = 4
                }
                if (cmd === 0 && this.state.activationPrice < quote) {
                    newCmd = 12
                }
                this.setState({cmd: newCmd})
            })
        }
    };

    validateVolume = volume => {
        return validatePrice(volume) && String(volume).length < 7
    };

    getRequiredMargin = () => {
        const {order: {symbol}, quote: {ask, bid}} = this.props;
        const {volume, activationPrice, cmd} = this.state;
        let price = 0;
        if (orderIsActive(cmd)) {
            if (!orderIsBuy(cmd)) {
                price = bid
            }
            if (orderIsBuy(cmd)) {
                price = ask
            }
        }
        if (!orderIsActive(cmd)) {
            price = activationPrice
        }
        return getOrderRequireMargin({symbol, volume, open_price: price})
    };

    setOrderType = type => {
        const {activationPrice} = this.state;
        const {cmd} = this.props.order;
        const {quote: {ask, bid}} = this.props;
        const quote = cmd === 0 ? ask : bid;
        let newCmd;

        if (type === "active") {
            newCmd = cmd
        }

        if (type === "pending") {
            if (cmd === 1 && activationPrice >= quote) {
                newCmd = 13
            }
            if (cmd === 1 && activationPrice < quote) {
                newCmd = 5
            }
            if (cmd === 0 && activationPrice >= quote) {
                newCmd = 4
            }
            if (cmd === 0 && activationPrice < quote) {
                newCmd = 12
            }
        }
        this.setState({cmd: newCmd})
    };

    updateOrder = data => {
        this.stops = data;
    };

    onSubmit = () => {

        const {asset, order, formType, settings} = this.props;
        const {volume, activationPrice, slIsEnable, tpIsEnable, cmd} = this.state;
        const {sl, tp, ts} = this.stops;
        const isActiveOrder = orderIsActive(cmd);

        if (asset.marketState === "closed" || this.state.disabled) {
            return false
        }
        this.setState({disabled: true});
        this.state.disabled = true;
        // if((!isActiveOrder && !activationPrice.length || !isActiveOrder && !parseFloat(activationPrice))) {
        //     return false
        // }


        let query = {
            symbol: order.symbol,
            volume,
            sl: slIsEnable ? sl : 0,
            tp: tpIsEnable ? tp : 0,
            cmd
        };

        if (this.state.expiration) {
            query.expiration = this.state.expiration + settings.serverUTCTimeOffset;
        }
        else
            query.expiration = null;


        if (formType === "modify") {
            if (!orderIsActive(cmd)) {
                query.price = parseFloat(activationPrice)
            }
            query = {...order, ...query}
        }

        if (formType === "open") {
            if (ts) {
                query.ts = ts
            }
            if (!orderIsActive(cmd)) {
                query.price = parseFloat(activationPrice)
            }
        }

        if (formType === "open") {
            return openOrder(query)
                .then(this.props.hide)
        }
        if (formType === "modify") {
            return modifyOrder(query)
                .then(this.props.hide)
        }
    };

    render() {
        const {order = {}, quote: {ask, bid}, asset, user, formType, settings} = this.props;
        let {volume, tpIsEnable, slIsEnable, activationPrice, cmd, disabled, expirationShow} = this.state;
        const {volumeMin, volumeMax, volumeStep, contract_size, digits} = asset;
        const requiredMargin = this.getRequiredMargin();
        const pipValue = getPipsForVolume({symbol: order.symbol, volume, ask, bid});
        const spread = getAssetSpreadInPoints({digits, ask, bid});
        const spreadInUserCurrency = spread * pipValue;
        const swap = getOrderSwap({symbol: order.symbol, ask, bid, volume});
        const profileCurrency = user[0].currency;
        const isActiveOrder = orderIsActive(cmd);
        const isBuyOrder = orderIsBuy(cmd);
        const open_price = isActiveOrder ? (isBuyOrder ? ask : bid) : activationPrice;
        const commission = getOrderCommission({
            resultAt: "number",
            profileCurrency,
            asset,
            volume,
            open_price
        });

        let tabDisplay1 = formType === "open" || (formType === "modify" && isActiveOrder);
        let tabDisplay2 = formType === "open" || (formType === "modify" && !isActiveOrder);


        return (
            <div className="openOrder">
                <div className="modal-tabs">
                    {formType === "open" && tabDisplay1 && (
                        <div className={classNames({
                            "modal-tabs-item": true,
                            "active": isActiveOrder
                        })} onClick={() => {
                            this.setOrderType("active")
                        }}>
                            <Lang>INSTANT_EXECUTION</Lang>
                        </div>
                    )}
                    {formType === "open" && tabDisplay2 && (
                        <div className={classNames({
                            "modal-tabs-item": true,
                            "active": !isActiveOrder
                        })} onClick={() => {
                            this.setOrderType("pending")
                        }}>
                            <Lang>PENDING_ORDER</Lang>
                        </div>
                    )
                    }
                </div>


                <div className="openOrder-body">
                    <div className="openOrder-row">
                        <div className="openOrder-row-box">
                            <div className="openOrder-field-title">
                                <div className="title-m">
                                    <Lang>BID</Lang>: {bid.toFixed(digits)}
                                </div>
                            </div>
                        </div>
                        <div className="openOrder-row-box">
                            <div className="openOrder-field-title">
                                <div className="title-m">
                                    <Lang>ASK</Lang>: {ask.toFixed(digits)}
                                </div>
                            </div>
                        </div>
                    </div>


                    {
                        !isActiveOrder && (
                            <div className="openOrder-row column">
                                <div className="row justify-flex-start content-middle pt-sm pb-sm">
                                    <div className="checkbox">
                                        <label className="checkbox">
                                            <input type="checkbox" checked={expirationShow}/>
                                            <span
                                                className="checkmark"
                                                onClick={() => {
                                                    this.setState({
                                                        expirationShow: !expirationShow
                                                    })
                                                }}
                                            />
                                        </label>
                                    </div>
                                    <div className="ml-md">
                                        <Lang>EXPIRATION</Lang>
                                    </div>
                                </div>

                                <div className="row justify-space-between">
                                    <div className="row justify-space-between content-middle">
                                        <div className="mr-sm">
                                            <b className="title-m">
                                                <Lang>PRICE</Lang>
                                            </b>
                                        </div>
                                        <input
                                            type="text"
                                            value={activationPrice}
                                            onInput={this.onInputActivationPrice}
                                        />
                                    </div>
                                    {expirationShow && <div className="row justify-space-between content-middle">
                                        <div className="mr-sm">
                                            <b className="title-m">
                                                <Lang>EXPIRATION</Lang>
                                            </b>
                                        </div>
                                        <Fields.date
                                            time
                                            name="date"
                                            format="DD.MM.YYYY HH:mm"
                                            // label="Date"
                                            ref={e => this.dateSelect = e}
                                            //
                                            value={(order.expiration - settings.serverUTCTimeOffset) * 1000  || Date.now()}
                                            onChange={(d) => {
                                                window.mom = d;
                                                console.log(d.valueOf());
                                                this.state.expiration = parseInt(d.valueOf() / 1000);
                                            }}
                                        />
                                    </div>}
                                </div>
                            </div>
                        )
                    }


                    <div className="openOrder-row">
                        <div className="openOrder-field">
                            <div className="openOrder-field-title">
                                <div className="title-m">
                                    <Lang>VOLUME</Lang>
                                </div>
                            </div>
                            <InputStep
                                className="input-volume"
                                value={volume}
                                valueMin={volumeMin}
                                valueMax={volumeMax}
                                valueStep={volumeStep}
                                validate={this.validateVolume}
                                onChange={this.onChangeVolume}
                                readOnly={formType === "modify"}
                            />
                        </div>
                        <div className="openOrder-field">
                            <div className="openOrder-field-title">
                                <div className="title-m">
                                    <Lang>CONTRACT_SIZE</Lang>
                                </div>
                                <div className="title-s">{asset.currency}</div>
                            </div>
                            <input
                                type="text"
                                // value={(volume * contract_size * getMultiplier({symbol: order.symbol})).toFixed(2)}
                                value={(volume * contract_size).toFixed(2)}
                                readOnly={true}
                            />
                        </div>
                        <div className="openOrder-field">
                            <div className="openOrder-field-title">
                                <div className="title-m">
                                    <Lang>MARGIN</Lang>
                                </div>
                                <div className="title-s">{user[0].currency}</div>
                            </div>
                            <input
                                type="text"
                                value={requiredMargin.toFixed(2)}
                                readOnly={true}
                            />
                        </div>
                    </div>
                    <div className="openOrder-row">
                        <div className="openOrder-calculation-item">
                            <div className="title">
                                <Lang>SPREAD</Lang>
                            </div>
                            <div className="value">
                                {`-${spreadInUserCurrency.toFixed(2)} ${user[0].currency}`}
                            </div>
                            <div className="value">
                                {`( ${spread.toFixed(1)} pips )`}
                            </div>
                        </div>
                        <div className="openOrder-calculation-item">
                            <div className="title">
                                <Lang>COMMISSION</Lang>
                            </div>
                            <div className="value">
                                {`${commission.toFixed(2)} ${getCurrencySymbol(profileCurrency)}`}
                            </div>
                        </div>
                        <div className="openOrder-calculation-item">
                            <div className="title">
                                <Lang>PIP_VALUE</Lang>
                            </div>
                            <div className="value">
                                {`${pipValue.toFixed(4)} ${user[0].currency}`}
                            </div>
                        </div>
                        <div className="openOrder-calculation-item">
                            <div className="title">
                                <Lang>DAILY_SWAP</Lang>
                            </div>
                            <div className="value">
                                <Lang>SELL</Lang>{`: ${swap.toFixed(2)} ${user[0].currency}`}
                            </div>
                            <div className="value">
                                <Lang>BUY</Lang>{`: ${swap.toFixed(2)} ${user[0].currency}`}
                            </div>
                        </div>
                    </div>
                    <div className="openOrder-row">
                        <div className="openOrder-stops-item">
                            <label className="checkbox">
                                <input type="checkbox" checked={slIsEnable}/>
                                <span
                                    className="checkmark"
                                    onClick={() => {
                                        this.setState({
                                            slIsEnable: !slIsEnable
                                        })
                                    }}
                                />
                            </label>
                            <div className="title">
                                <Lang>STOP_LOSS</Lang>
                            </div>
                        </div>
                        <div className="openOrder-stops-item">
                            <div className="title">
                                <Lang>TAKE_PROFIT</Lang>
                            </div>
                            <div className="checkbox">
                                <label className="checkbox">
                                    <input type="checkbox" checked={tpIsEnable}/>
                                    <span
                                        className="checkmark"
                                        onClick={() => {
                                            this.setState({
                                                tpIsEnable: !tpIsEnable
                                            })
                                        }}
                                    />
                                </label>
                            </div>
                        </div>
                    </div>
                    {
                        (slIsEnable || tpIsEnable) && (
                            <div className="openOrder-row">
                                <TpSlForm
                                    order={{
                                        slIsEnable,
                                        tpIsEnable,
                                        symbol: order.symbol,
                                        volume,
                                        cmd,
                                        sl: order.sl,
                                        tp: order.tp,
                                        bid: bid,
                                        ask: ask,
                                        open_price: order['open_price'] || (!isActiveOrder ? activationPrice : orderIsBuy(cmd) ? ask : bid)
                                    }}
                                    onChange={this.updateOrder}
                                    formType={formType}
                                />
                            </div>
                        )
                    }
                    <div className="openOrder-row">
                        <div className="openOrder-submit">
                            <div className={classNames({
                                "openOrder-button": true,
                                "sell": !orderIsBuy(order.cmd),
                                "buy": orderIsBuy(order.cmd),
                                "disabled": disabled
                                // "disabled": asset.marketState === "closed" || (!isActiveOrder && !activationPrice.length || !isActiveOrder && !parseFloat(activationPrice))
                            })} onClick={this.onSubmit}>
                                {formType === "modify" && <Lang>MODIFY</Lang>} {!orderIsBuy(order.cmd) &&
                            <Lang>SELL</Lang>}{orderIsBuy(order.cmd) && <Lang>BUY</Lang>}
                                {isActiveOrder && <span className="openOrder-price">
                                    {orderIsBuy(order.cmd) ? ask.toFixed(digits) : bid.toFixed(digits)}
                                </span>}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
