import React, {Component} from 'react';
import { connect } from "react-redux";
import { merge } from 'lodash';
import Testable from './Testable';
import withTemporaryId from './withTemporaryId';
import {conditions, filters} from './conditionsOrFilters/CardCreator';
import ContextActions from './actions/ContextActions';
import Tippy from '@tippyjs/react/headless'; 
import classNames from 'classnames';
import Offer from './conditionsOrFilters/Offer';
import ContextPopup from './ContextPopup';
import Popup from './Popup';

const {newConditionOrFilter} = ContextActions;


class Context extends Component
{
    state = {
        panelIsOpen: false
    };

    static structure = () => withTemporaryId({
        "conditionsOrFilters": [],
        "offers": []
    });

    static map(context) 
    {
        const newContext =  merge({}, Context.structure(), context);
        newContext.offers = context.offers.map(offer => Offer.map(offer))

        return newContext;
    }

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

    componentDidUpdate() 
    {
        if (this.state.panelIsOpen) {

        }
    }

    render() 
    {
        return (
            <div className={classNames({
                'flex flex-col space-y-4 justify-center items-center': true,
                'pr-4': !this.props.hasMoreColumnsToTheRight && !this.props.disableMarginRight
            })}>
                {!this.hasConditionsOrFilters()? (
                    this.props.noConditionsOrFilterRender? this.props.noConditionsOrFilterRender() : <div className="relative flex flex-col justify-center items-center space-y-3 text-gray-400">
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-9 w-9" viewBox="0 0 20 20" fill="currentColor">
                          <path d="M10 3.5a1.5 1.5 0 013 0V4a1 1 0 001 1h3a1 1 0 011 1v3a1 1 0 01-1 1h-.5a1.5 1.5 0 000 3h.5a1 1 0 011 1v3a1 1 0 01-1 1h-3a1 1 0 01-1-1v-.5a1.5 1.5 0 00-3 0v.5a1 1 0 01-1 1H6a1 1 0 01-1-1v-3a1 1 0 00-1-1h-.5a1.5 1.5 0 010-3H4a1 1 0 001-1V6a1 1 0 011-1h3a1 1 0 001-1v-.5z" />
                        </svg>
                        <h1 className="text-2x text-gray-400">{__('No Conditions or Filters!',window.CouponsPlus.textDomain)}</h1>
                    </div>
                ): ''}
                {this.props.data.conditionsOrFilters.map(conditionOrFilter => {
                    return <Testable 
                                key={conditionOrFilter.temporaryID} 
                                conditionOrFilter={conditionOrFilter} 
                                testableType={this.getTestableType()}
                                contextTemporaryID={this.props.data.temporaryID}
                                columnTemporaryID={this.props.columnData.temporaryID}
                            />;
                })}
                {this.getPopOver()}
            </div>
        );
    }

    getTestableType() 
    {
        if (typeof this.props.supportsOnlyThisTestableType !== 'undefined') {
            return this.props.supportsOnlyThisTestableType
        }

        return this.props.testableType    
    }

    getPopOver()
{
        return (<div className="flex flex-row items-center space-x-2">
                {this.canAddEitherTestableType() || this.getTestableType() === 'conditions' ? <Popup
                    content={() => (<ContextPopup 
                        conditionsOrFilters={conditions} 
                        numberOfColumns={2} 
                        data={this.props.data}
                        handleConditionOrFilterClick={this.handleConditionOrFilterClick.bind(this)}
                    />)}
                    Button={() => (<button className={classNames(
                        'space-x-1 items-center justify-center',
                        {
                            'flex flex-row py-1 text-gray-400': this.hasConditionsOrFilters(),
                            'inline-flex bg-blue-normal text-gray-100 px-8 h-8 rounded-1  mt-2': !this.hasConditionsOrFilters()
                        })
                    }>
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clipRule="evenodd" />
                        </svg>
                        <span className="whitespace-nowrap">{CouponsPlus.text.add.conditions}</span>
                    </button>)}
                /> : ''}
                {this.canAddEitherTestableType() || this.getTestableType() === 'filters'? <Tippy
                    allowHTML={true}
                    followCursor={true}
                    placement="auto-end"
                    interactive={true}
                    visible={this.state.panelIsOpen}
                    onClickOutside={() => this.setState({panelIsOpen: false})}
                    render={attrs => (
                        <ContextPopup 
                            conditionsOrFilters={filters} 
                            numberOfColumns={1} 
                            data={this.props.data}
                            handleConditionOrFilterClick={this.handleConditionOrFilterClick.bind(this)}
                            testableType={'filters'}
                            width="w-[240px]"
                        />
                    )}
                >
                    <button className={classNames(
                        'space-x-1 items-center justify-center',
                        {
                            'flex flex-row py-1 text-gray-400': this.hasConditionsOrFilters(),
                            'inline-flex bg-blue-shade-100 text-gray-100 px-8 h-8 rounded-1 mt-2': !this.hasConditionsOrFilters()
                        })
                    } onClick={() => this.setState({panelIsOpen: true})}>
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clipRule="evenodd" />
                        </svg>
                        <span className="whitespace-nowrap">{CouponsPlus.text.add.filters}</span>
                    </button>
                </Tippy> : ''}
               </div>)
    }

    canAddEitherTestableType() 
    {
        return !this.hasConditionsOrFilters() && typeof this.props.supportsOnlyThisTestableType === 'undefined'
    }

    handleConditionOrFilterClick(conditionOrFilter)
    {
        this.props.newConditionOrFilter(
            conditionOrFilter.constructor.TYPE,
            this.props.data.temporaryID,
            this.props.columnData.temporaryID
        )

        this.setState({panelIsOpen: false})
    }

    hasConditionsOrFilters()
    {
        return this.props.data.conditionsOrFilters.length;
    }
}

export default connect(Context.mapStateToProps, {newConditionOrFilter})(Context);