import React, {Component} from 'react';
import {Provider} from 'sbx-react-core';
import Icon from "sbx-react-icon";
import classNames from "classnames";

import _ from "underscore";

import {
    setSetting,
    getSetting,
    addChart,
    setChart
} from 'actions/Settings';

import {openOrder} from 'actions/Orders';
import {setAssetsGroup} from "actions/Interface";

import './styles/index.scss';

import Lang from 'components/Language';

import AssetBox from "./components/AssetBox";
import AssetsGroups from "./components/AssetsGroups";
import AssetsSearch from "./components/AssetsSearch";
import MiniTradePanel from "containers/TradePanel/MiniTradePanel";

const menu = require('../../assets/icons/menu.svg');
const columns = require('../../assets/icons/columns.svg');
const arrowTop = require("./assets/arrow.svg");
const caretUp = require("./assets/caret-up.svg");
const caretDown = require("./assets/caret-down.svg");

@Provider({
    assets: ['assets'],
    groups: ['groups'],
    settings: ['settings']
})

export default class Markets extends Component {
    state = {
        symbols: [],
        isExpanded: false,
        expandedSymbol: false,
        sort: {
            type: this.props.settings.group === "ALL" ? "category" : "name",
            reverse: false
        },
        scrollToMarket: false
    };
    customGroups = ["favorites", "popular"];
    timeout = false;

    componentDidMount() {
        const {settings} = this.props;
        this.setState({
            symbols: this.getMarketList(settings.group)
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        const {favourites, group} = this.props.settings;
        if(
            group === "favorites" &&
            Array.isArray(favourites) &&
            Array.isArray(nextProps.settings.favourites) &&
            favourites.length !== nextProps.settings.favourites.length
        ) {
            return this.setState({
                sort: {type: 'name', reverse: false},
                symbols: this.getMarketList("favorites",  nextProps.settings.favourites),
                expandedSymbol: false
            })
        }
        if(nextProps.settings.group !== this.props.settings.group) {
            if(nextProps.settings.group === "ALL") {
                return this.setState({sort: {type: 'category', reverse: false}}, () => {
                    this.setState({
                        symbols: this.getMarketList(nextProps.settings.group)
                    })
                })
            } else {
                return this.setState({sort: {type: 'name', reverse: false}}, () => {
                    this.setState({
                        symbols: this.getMarketList(nextProps.settings.group),
                        expandedSymbol: false
                    })
                })
            }
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        const {scrollToMarket} = this.state;
        const {group} = this.props.settings;
        if(scrollToMarket && this.expandedSymbol) {
            this.setState({scrollToMarket: false}, () => {
                this.expandedSymbol.scrollIntoView({block: "center"});
            })
        } else if(group !== prevProps.settings.group) {
            this.marketList.scrollTo(0, 0)
        }
    }

    getMarketList = (group, favouritesList) => {
        const {sort} = this.state;
        const {assets, settings, groups} = this.props;
        const favourites = settings.favourites && Array.isArray(settings.favourites);
        const popular = settings.popular && Array.isArray(settings.popular);
        let symbols = [];


        if(group === "ALL") {
            symbols = Object.values(assets).filter(asset => !asset.hidden).map(i => i.symbol)
        } else {
            if(this.customGroups.includes(group)) {
                if(group === "favorites" && favourites && settings.favourites.length) {
                    symbols = Object.values(assets)
                        .filter(asset => !asset.hidden && (favouritesList || settings.favourites).includes(asset.symbol))
                        .map(asset => asset.symbol)
                }

                if(group === "popular" && popular && settings.popular.length) {
                    symbols = Object.values(assets)
                        .filter(asset => !asset.hidden && settings.popular.includes(asset.symbol))
                        .map(asset => asset.symbol)
                }
            } else {
                Object.keys(assets).forEach(symbol => {
                    const isHidden = assets[symbol].hidden;
                    if(!isHidden && assets[symbol].groups[0] === group) {
                        symbols.push(symbol)
                    }
                });
            }
        }


        if(sort.type === "name") {
            symbols = symbols.sort()
        }

        if(sort.type === "category") {

            // symbols = _.sortBy(symbols, (sym)=>{
            //     return assets[sym].groups[0]
            // });
            symbols = groups.map(group => {
                return Object.values(assets).filter(asset => {
                    return asset.groups[0] === group && !asset.hidden
                }).map(asset => asset.symbol)
            });
            symbols = symbols.flat()
        }


        if(sort.type === "ask") {
            symbols = symbols.sort((a, b) => {
                return assets[a].ask - assets[b].ask
            })
        }

        if(sort.type === "bid") {
            symbols = symbols.sort((a, b) => {
                return assets[a].bid - assets[b].bid
            })
        }

        if(sort.reverse) {
            symbols = symbols.reverse()
        }

        return symbols;
    };

    setSort = type => {
        return this.setState({
            sort: {type, reverse: !this.state.sort.reverse}}, () => {
                this.setState({
                    symbols: this.getMarketList(this.props.settings.group)
                })
        })
    };

    expand = () => {
        this.setState({isExpanded: !this.state.isExpanded, expandedSymbols: []})
    };

    addToExpandedSymbols = symbol => {
        const {expandedSymbol} = this.state;
        if(expandedSymbol !== symbol) {
            this.setState({expandedSymbol: symbol})
        } else {
            this.setState({expandedSymbol: false})
        }
    };

    onSearchSelect = symbol => {
        setSetting({setting: 'group', value: 'ALL'}, () => {
            this.setState({expandedSymbol: symbol, scrollToMarket: true})
        })
    };

    handleClick = (e, symbol) => {
        e.preventDefault();
        if(!this.timeout) {
           return this.timeout = setTimeout(() => {
               this.__onClick(symbol);
               clearTimeout(this.timeout);
               this.timeout = false;
           }, 200);
        }
        this.timeout = clearTimeout(this.timeout);
        return this.__onDoubleClick(symbol)
    };

    __onClick = symbol => {
        this.addToExpandedSymbols(symbol);
    };

    __onDoubleClick = symbol => {
        setChart(symbol)
    };

    render() {
        const {group} = this.props.settings;
        const {symbols, isExpanded, expandedSymbol, sort, scrollToMarket} = this.state;

        return (
            <>
                <AssetsGroups/>
                <div className="markets-topPanel">
                    <AssetsSearch
                        inputAnimate={!symbols.length && group === "favorites"}
                        onSelect={this.onSearchSelect}
                    />
                    <Icon src={!isExpanded ? menu : columns} onClick={this.expand}/>
                </div>

                <div ref={e => this.marketList = e} className={classNames({
                    "markets-list": true,
                    "expanded": isExpanded,
                    "markets-list-empty": !symbols.length
                })}>
                    {
                        !isExpanded && symbols.length > 1 && (
                            <div className="markets-list-header">
                                {/*<div*/}
                                {/*className="markets-list-header-item"*/}
                                {/*onClick={() => {*/}
                                {/*this.setSort("category")*/}
                                {/*}}*/}
                                {/*>*/}
                                {/*<span>*/}
                                {/*Cat*/}
                                {/*{sort.type === "category" && <Icon src={sort.reverse ? caretDown : caretUp}/>}*/}
                                {/*</span>*/}
                                {/*</div>*/}
                                <div
                                    className="markets-list-header-item"
                                >
                                        <span onClick={() => {
                                            this.setSort("name")
                                        }}>
                                            <Lang>SYMBOL</Lang>
                                            {sort.type === "name" && <Icon src={sort.reverse ? caretDown : caretUp}/>}
                                        </span>

                                    {group === "ALL"&& <span className={"ml-xs"} onClick={() => {
                                        this.setSort("category")
                                    }}>
                                            <Lang>CATEGORY</Lang>
                                        {sort.type === "category" && <Icon src={sort.reverse ? caretDown : caretUp}/>}
                                        </span>}
                                </div>
                                <div
                                    className="markets-list-header-item"
                                    // onClick={() => {
                                    //     this.setSort("change")
                                    // }}
                                >
                                        <span>
                                            <Lang>CHANGHE_1D</Lang>
                                            {/*{sort.type === "change" && <Icon src={sort.reverse ? caretDown : caretUp}/>}*/}
                                        </span>
                                </div>
                                <div
                                    className="markets-list-header-item"
                                    onClick={() => {
                                        this.setSort("bid")
                                    }}
                                >
                                        <span>
                                            <Lang>BID</Lang>
                                            {sort.type === "bid" && <Icon src={sort.reverse ? caretDown : caretUp}/>}
                                        </span>
                                </div>
                                <div
                                    className="markets-list-header-item"
                                    onClick={() => {
                                        this.setSort("ask")
                                    }}
                                >
                                        <span>
                                            <Lang>ASK</Lang>
                                            {sort.type === "ask" && <Icon src={sort.reverse ? caretDown : caretUp}/>}
                                        </span>
                                </div>
                            </div>
                        )
                    }
                    {!symbols.length && !this.customGroups.includes(group) && (
                        <div className="market-message">
                            <Lang>NO_FOUND_ASSET</Lang>
                        </div>
                    )}
                    {
                        !symbols.length && group === "favorites" && (
                            <div className="favorites-empty">
                                <div className="favorites-empty-icon">
                                    <Icon src={arrowTop}/>
                                </div>
                                <div className="favorites-empty-title">
                                    <Lang>LIST_OF_FAV_TITLE</Lang>
                                </div>
                                <div className="favorites-empty-subtitle">
                                    <Lang>LIST_OF_FAV_DESC</Lang>
                                </div>
                            </div>
                        )
                    }
                    {
                        symbols.map((symbol, i) => {
                            if(!isExpanded) {
                                return (
                                    <>
                                        <div
                                            key={symbol}
                                            ref={e => expandedSymbol === symbol ? this.expandedSymbol = e : false}
                                            className={classNames({
                                                "market-list-row": true,
                                                "expanded": isExpanded || expandedSymbol === symbol
                                            })}
                                            onClick={e => {
                                                this.handleClick(e, symbol)
                                            }}
                                        >
                                            {
                                                expandedSymbol !== symbol && (
                                                    <AssetBox
                                                        symbol={symbol}
                                                    />
                                                )
                                            }{
                                                expandedSymbol === symbol && (
                                                    <MiniTradePanel
                                                        symbol={symbol}
                                                    />
                                                )
                                            }
                                        </div>
                                    </>
                                )
                            } else {
                                return (
                                    <div
                                        className={classNames({
                                            "market-list-row": true,
                                            "expanded": true,
                                            "no-hover": i === this.state.hover + 1
                                        })}
                                        ref={e => expandedSymbol === symbol ? this.expandedSymbol = e : false}
                                    >
                                        <MiniTradePanel
                                            key={symbol}
                                            symbol={symbol}
                                        />
                                    </div>
                                )
                            }
                        })
                    }
                </div>
            </>
        );
    }
}
