import React, {Component} from 'react';
import _ from 'lodash';
import { invert } from 'lodash';
import ColumnsRegistrator from './columns/ColumnsRegistrator';
import { connect } from "react-redux";
import Context from './Context';
import withTemporaryId from './withTemporaryId';
import RowActions from './actions/RowActions';
import classNames from 'classnames';
import { __ } from './globals';

const {removeColumn} = RowActions;

class Column extends Component
{
    static structure = () => withTemporaryId({
        "type": "",
        "testableType": "",
        "defaultOffers": [
        ],
        "contexts": [
        ]
    });

    state = {
        isHoveringButton: false
    };

    static map(column) 
    {
        return _.merge({}, Column.structure(), column);
    }

    static mapStateToProps(state, props) {
        return {data: Column.map(props.data), ...state,}
    };

    render() 
    {
        const Column = this.getColumnComponent();
        return (
            <div className={classNames({
                'flex flex-col space-y-5 first:pl-0': true,
                'min-w-70': this.props.supportsMultipleColumns,
                'pr-6': this.props.isTheFirstColumn,
                'px-6': !this.props.isTheFirstColumn,
                'border-r-2 border-dashed border-gray-350': this.props.hasMoreColumnsToTheRight
            })}>
                {this.props.supportsMultipleColumns && <header className="flex flex-row justify-end items-center space-x-2">
                    <span className="text-gray-350 flex flex-col items-end">
                        <span className="bg-gray-250 text-gray-400 rounded-6 px-1">{Column.getMeta()?.name} {__('Column', window.CouponsPlus.textDomain)}</span>
                        {Column.TYPE ===window.CouponsPlus.components.columns.TieredOffers.type && <span className="text-smaller-2 text-gray-400">
                            {__('Mode: ')}<b className="">{invert(CouponsPlus.components.defaultColumnOptions.executionOrderMode.meta._allowed)[this.props.data.executionOrderMode]}</b>
                        </span>}
                    </span>
                    <button 
                        className="bg-gray-300 text-transparent hover:bg-gray-400 hover:text-gray-100 h-5 px-3 rounded-full"
                        onMouseEnter={() => this.setState({isHoveringButton: true})}
                        onMouseLeave={() => this.setState({isHoveringButton: false})}
                        onClick={() => this.props.removeColumn(
                            this.props.rowData.temporaryID,
                            this.props.data.temporaryID
                        )}
                    >
                        {this.state.isHoveringButton? __('Remove column',window.CouponsPlus.textDomain) : __('Remove',window.CouponsPlus.textDomain)}
                    </button>
                </header>}
                <Column 
                    getContextComponents={(extraContextProps) => this.getContexts().map(contextData => ([
                            (<Context 
                                key={contextData.temporaryID} 
                                data={contextData} 
                                testableType={this.props.data.testableType}
                                supportsOnlyThisTestableType={this.props.testableType}
                                columnData={this.props.data}
                                hasMoreColumnsToTheRight={this.props.hasMoreColumnsToTheRight}
                                noConditionsOrFilterRender={this.props.noConditionsOrFilterRender}
                                {...(extraContextProps || {})}
                                disableMarginRight={!this.props.supportsMultipleColumns}
                            />),
                            contextData,
                        ]))
                    } 
                    columnNumber={this.props.columnNumber}
                    columnData={this.props.data}
                    hasMoreColumnsToTheRight={this.props.hasMoreColumnsToTheRight}
                    isTheFirstColumn={this.props.isTheFirstColumn}
                    supportsMultipleColumns={this.props.supportsMultipleColumns}
                />
            </div>
        );
    }

    getColumnComponent() 
    {
        return ColumnsRegistrator.getAll().find(Column => Column.TYPE === this.props.data.type);
    }

    getContexts() 
    {
        const contexts = this.props.data.contexts;

        if (!Array.isArray(contexts)) {
            console.error(__('Row prop: rowData isnt an array (and it needs to be, fallbacking to an empty array)',window.CouponsPlus.textDomain));
            return [];
        }   

        return contexts;
    }
}

export default connect(Column.mapStateToProps, {removeColumn})(Column);