import React, { Component } from 'react';
import { DropdownDesktop } from '../../atom/DropdownDesktop/DropdownDesktop';

import PropTypes from 'prop-types';
/**
 * A statefull component of Desktop to create PaxConfig overlay atom which will enable user to configure Pax and rooms.
 */
class DesktopPaxConfig extends Component {
    constructor(props) {
        super(props);
        this.removeRooms = this.removeRooms.bind(this);
        this.disableDiv = this.disableDiv.bind(this);
        this.enableDiv = this.enableDiv.bind(this);
        this.increment = this.increment.bind(this);
        this.decrement = this.decrement.bind(this);
        this.onChange = this.onChildAgeChange.bind(this);
        this.incrementch = this.incrementch.bind(this);
        this.decrementch = this.decrementch.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.handleKeyDown = this.handleKeyDown.bind(this);
        this.handleOutsideClick = this.handleOutsideClick.bind(this);
        this.updateFocusOut = this.updateFocusOut.bind(this);
        this.handleKeyEsc = this.handleKeyEsc.bind(this);
        this.state = {
            popupVisible: false,
            rooms: [{ room: 1, adult: this.props.defaultAdult, children: this.props.defaultChild, child: [], childincrement: this.props.maxChild !== this.props.defaultChild ? true : false, childecrement: this.props.minChild !== this.props.defaultChild ? true : false, fontimg: this.props.minChild !== this.props.defaultChild ? true : false, adultincrement: this.props.maxAdult !== this.props.defaultAdult ? true : false, adultdecrement: this.props.minAdult !== this.props.defaultAdult ? true : false }],
            count: 2,
            adult: this.props.defaultAdult,
            children: this.props.defaultChild,
            room: 1,
            img: true,
            buttoncolor: true,
        };


    }
    removeRooms(index) {
        var asd = [...this.state.rooms];
        if (this.state.rooms.length > 1) {
            asd.forEach((a) => {
                a.adultincrement = true;
                a.childincrement = true;
                if (a.adult === this.props.maxAdult) {
                    a.adultincrement = false;
                } else if (a.children === this.props.maxChild) {
                    a.childincrement = false;
                }
            });
            this.setState({
                buttoncolor: true
            });
            this.state.rooms.splice(index, 1);
            this.setState({ rooms: this.state.rooms });
            // this.setState({
            //     popupVisible: false
            // });
        }
    }
    addRooms() {
        var c = 0;
        this.state.rooms.forEach((fact, index) => {
            c = c + fact.adult + fact.children;
        });
        if (this.state.rooms.length < this.props.maximumRooms && c < this.props.totalPax) {
            this.disableDiv();
            this.setState({ count: this.state.count + 1 });
            var add1 = [...this.state.rooms];
            if (this.props.defaultAdult + this.props.defaultChild + c < this.props.totalPax) {
                add1.push({ room: this.state.count, adult: this.props.defaultAdult, children: this.props.defaultChild, child: [], childincrement: this.props.maxChild !== this.props.defaultChild ? true : false, childecrement: this.props.minChild !== this.props.defaultChild ? true : false, fontimg: this.props.minChild !== this.props.defaultChild ? true : false, adultincrement: this.props.maxAdult !== this.props.defaultAdult ? true : false, adultdecrement: this.props.minAdult !== this.props.defaultAdult ? true : false });
            }
            else if (this.props.defaultAdult + this.props.defaultChild + c === this.props.totalPax) {
                add1.push({ room: this.state.count, adult: this.props.defaultAdult, children: this.props.defaultChild, child: [], childincrement: false, childecrement: this.props.minChild !== this.props.defaultChild ? true : false, fontimg: this.props.minChild !== this.props.defaultChild ? true : false, adultincrement: false, adultdecrement: this.props.minAdult !== this.props.defaultAdult ? true : false });
                this.setState({
                    buttoncolor: false
                });
                add1.forEach((a) => {
                    a.adultincrement = false;
                    a.childincrement = false;
                });
            }
            else {
                for (var i = 1; i < this.props.defaultAdult + this.props.defaultChild; i++) {
                    if (c + i === this.props.totalPax) {
                        add1.push({ room: this.state.count, adult: i, children: 0, child: [], childincrement: false, childecrement: this.props.minChild !== this.props.defaultChild ? true : false, fontimg: this.props.minChild !== this.props.defaultChild ? true : false, adultincrement: false, adultdecrement: this.props.minAdult !== i ? true : false });
                        this.setState({
                            buttoncolor: false
                        });
                        add1.forEach((a) => {
                            a.adultincrement = false;
                            a.childincrement = false;
                        });
                    }
                }
            }
            this.setState({ rooms: add1 });
            if (this.state.rooms.length === this.props.maximumRooms - 1) {
                this.setState({
                    buttoncolor: false
                });
            }
        }
    }

    disableDiv() {
        var asd = this.state.rooms;
        asd.forEach((a) => {
            a.disableDiv = true;
        });
        this.setState({
            rooms: asd
        });

    }

    enableDiv(index) {
        var asd = this.state.rooms;
        asd.forEach((a) => {
            a.disableDiv = true;
        });
        asd[index].disableDiv = false;
        this.setState({
            rooms: asd
        });
    }
    onChildAgeChange(index, index1, e) {
        var asd = this.state.rooms;
        asd[index].child[index1].age = e.value;
        this.setState({
            rooms: asd
        });
    }
    increment(index) {
        var asd = this.state.rooms;
        var c = 0;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (asd[index].adult < this.props.maxAdult && c < this.props.totalPax) {
            if (asd[index].adult + asd[index].children < this.props.guestPerRooms) {
                asd[index].adult++;
                if (asd[index].adult + asd[index].children === this.props.guestPerRooms) {
                    asd[index].adultincrement = false;
                    asd[index].childincrement = false;
                }
                this.setState({
                    rooms: asd
                });
            }
        }
        if (asd[index].adult > this.props.minAdult) {
            asd[index].adultdecrement = true;
        }
        c = 0;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (c === this.props.totalPax) {
            this.setState({
                buttoncolor: false
            });
            asd.forEach((a) => {
                a.adultincrement = false;
                a.childincrement = false;
            });
        }
        if (asd[index].adult === this.props.maxAdult) {
            asd[index].adultincrement = false;
        }
    }
    incrementch(index) {
        var asd = [...this.state.rooms];
        var c = 0;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (asd[index].children < this.props.maxChild && c < this.props.totalPax) {
            if (asd[index].adult + asd[index].children < this.props.guestPerRooms) {
                asd[index].children++;
                if (asd[index].adult + asd[index].children === this.props.guestPerRooms) {
                    asd[index].adultincrement = false;
                    asd[index].childincrement = false;
                }
                asd[index].child.push({ age: 0 });
                this.setState({
                    rooms: asd
                });
            }
        }
        if (asd[index].children > this.props.minChild) {
            asd[index].childecrement = true;
            asd[index].fontimg = true;
        }
        if (asd[index].children === this.props.maxChild) {
            asd[index].childincrement = false;
        }
        c = 0;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (c === this.props.totalPax) {

            this.setState({
                buttoncolor: false
            });
            asd.forEach((a) => {
                a.adultincrement = false;
                a.childincrement = false;
            });
        }

    }
    updateFocusOut() {
        var paxconfigArray = [...this.state.rooms];
        var paxconfigArrayUser = [];
        var c = 0;
        var k = 0;
        paxconfigArray.forEach((fact) => {
            var child = [];
            c = c + fact.adult;
            k = k + fact.children;
            fact.child.forEach((children) => {
                child.push({ Age: children.age });
            });
            paxconfigArrayUser.push({ Room: fact.room, Adult: fact.adult, Children: fact.children, Child: child });
        });
        this.setState({
            adult: c
        });
        this.setState({
            children: k
        });
        this.setState({
            room: paxconfigArray.length
        });
        this.props.onBlurPaxConfigText(paxconfigArrayUser);
    }
    decrementch(index) {
        var asd = [...this.state.rooms];
        var c = 0;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (asd[index].children > this.props.minChild) {
            if (asd[index].children < this.props.maxChild) {
                asd[index].childincrement = true;
            }
            if (asd[index].adult < this.props.maxAdult) {
                asd[index].adultincrement = true;
            }
            asd[index].children--;
            asd[index].child.pop('');
            this.setState({
                rooms: asd
            });
            if (asd[index].children === this.props.minChild) {
                asd[index].fontimg = false;
                asd[index].childecrement = false;
            }
            if (asd[index].children < this.props.maxChild) {
                asd[index].childincrement = true;
            }
            this.setState({
                buttoncolor: true
            });


            if (c === this.props.totalPax) {

                asd.forEach((a) => {
                    if (a.adult < this.props.maxAdult) {
                        a.adultincrement = true;
                    }
                    if (a.children < this.props.maxChild) {
                        a.childincrement = true;
                    }
                    if (a.adult === this.props.maxAdult && a.children === this.props.minChild) {
                        a.adultincrement = false;
                        a.childincrement = false;
                    }
                });

            }
        }
        if (this.state.rooms.length === this.props.maximumRooms) {
            this.setState({
                buttoncolor: false
            });
        }
    }
    decrement(index) {
        var c = 0;
        var asd = this.state.rooms;
        asd.forEach((fact) => {
            c = fact.adult + fact.children + c;
        });
        if (asd[index].adult > this.props.minAdult) {
            if (asd[index].children < this.props.maxChild) {
                asd[index].childincrement = true;
            }
            if (asd[index].adult < this.props.maxAdult) {
                asd[index].adultincrement = true;
            }
            asd[index].adultincrement = true;
            asd[index].adult--;
            this.setState({
                rooms: asd
            });
            this.setState({
                buttoncolor: true
            });

            if (asd[index].adult === this.props.minAdult) {
                asd[index].adultdecrement = false;
            }
            if (c === this.props.totalPax) {

                asd.forEach((a) => {
                    if (a.adult < this.props.maxAdult) {
                        a.adultincrement = true;
                    }
                    if (a.children < this.props.maxChild) {
                        a.childincrement = true;
                    }
                    if (a.adult === this.props.maxAdult && a.children === this.props.minChild) {
                        a.adultincrement = false;
                        a.childincrement = false;
                    }
                });

            }
        }

        if (this.state.rooms.length === this.props.maximumRooms) {
            this.setState({
                buttoncolor: false
            });
        }
    }
    handleClick() {
        if (!this.state.popupVisible) {
            document.addEventListener('click', this.handleOutsideClick, false);
        } else {
            document.removeEventListener('click', this.handleOutsideClick, false);
        }
        this.setState(prevState => ({
            popupVisible: !prevState.popupVisible,
        }));
        this.setState(prevState => ({
            img: !prevState.img,
        }));
        this.updateFocusOut();
    }


    handleOutsideClick(e) {
        if (this.node.contains(e.target)) {
            return;
        }
        this.updateFocusOut();
        this.setState({
            img: false
        });
        this.handleClick();
    }
    //WA method
    handleKeyDown(event) {

        if (event.keyCode === 13) {
            this.setState(prevState => ({
                popupVisible: !prevState.popupVisible,
            }));

            this.setState(prevState => ({
                img: !prevState.img,
            }));
        }
        this.updateFocusOut();

    }
    handleKeyEsc(event) {
        if (event.keyCode === 27) {
            this.setState(prevState => ({
                popupVisible: !prevState.popupVisible,
            }));

            this.setState(prevState => ({
                img: !prevState.img,
            }));
        }
        this.updateFocusOut();

    }


    render() {

        return (
            <div className='jp-paxcongig-maincontainer' ref={node => { this.node = node; }}>
                <div className={this.state.img ? 'input-dropdownarrow' : 'input-dropduparrow'} role='presentation' onClick={this.handleClick}  >
                    <input type='text' aria-label='Pax config' className='jp-paxcongig-container' onKeyDown={(event) => this.handleKeyDown(event)} value={this.state.children !== 0 ? this.state.adult + ' Adult + ' + this.state.children + ' Children, ' + this.state.room + ' Room' : this.state.adult + ' Adult + ' + this.state.children + ' Child, ' + this.state.room + ' Room'} readOnly />
                </div>
                {
                    this.state.popupVisible && (
                        <div className='pexconfig-megadrop'>
                            <div className='allmembers-block'>
                                {
                                    this.state.rooms.map((fact, index) => {
                                        return (
                                            <div className='pax-padding' key={index}>
                                                <div className='pex-room'>
                                                    <div className='pex-room-title'>
                                                        <span className='roomsubtitle' aria-live='assertive'>ROOM {index + 1}    </span>
                                                    </div>
                                                    <div className='divider' />
                                                </div>
                                                <div className={!fact.disableDiv ? 'jp-divdisplay-block' : 'jp-divdisplay'}>
                                                    <div className='pex-room-data'>
                                                        <div className='leftpanel'><p><span>Adult </span>{this.props.adultAgeRangeLabel}</p></div>
                                                        <div className='rightpanel'>
                                                            <button onClick={() => this.decrement(index)} onKeyDown={(event) => this.handleKeyEsc(event)} className={fact.adultdecrement ? 'minusimage' : 'minusimage2'} aria-label={fact.adultdecrement ? 'minus adult' : ' minus adult button disable'} />
                                                            <div className='count' aria-live='assertive'>{fact.adult}</div>
                                                            <button onClick={() => this.increment(index)} onKeyDown={(event) => this.handleKeyEsc(event)} className={fact.adultincrement ? 'addimage' : 'addimage2'} aria-label={fact.adultincrement ? 'add adult' : 'add adult button disable'} />
                                                        </div>
                                                    </div>
                                                    <div className='pex-room-data'>
                                                        <div className='leftpanel'><div className='jp-childbold'><div className={fact.fontimg ? 'child-bold' : 'child-regular'}>Children</div> {this.props.childAgeRangeLabel}</div></div>
                                                        <div className='rightpanel-2'>
                                                            <button onClick={() => this.decrementch(index)} onKeyDown={(event) => this.handleKeyEsc(event)} className={fact.childecrement ? 'minusimage' : 'minusimage2'} aria-live='polite' aria-label={fact.childecrement ? 'minus children ' : 'minus children button disable'} />
                                                            <div className='count' aria-live='assertive' >{fact.children}</div>
                                                            <button onClick={() => this.incrementch(index)} onKeyDown={(event) => this.handleKeyEsc(event)} className={fact.childincrement ? 'addimage' : 'addimage2'} aria-label={fact.childincrement ? 'add children' : 'add children button disable'} />
                                                        </div>
                                                    </div>
                                                    <div className='pex-childmaindropdown'>
                                                        {fact.child.map((chfact, index1) => {
                                                            return (
                                                                <div className='pex-childdropdown ' id={'react-select-' + (index1 + 2) + '--value'} key={index1} >
                                                                    <p className='additionalchild' >Child {index1 + 1} Age</p>
                                                                    <DropdownDesktop
                                                                        id={'react-select-' + (index1 + 2) + '--value'}
                                                                        selectedDropdown='normalDropdown'
                                                                        value={chfact.age}
                                                                        options={this.props.paxAgeOptions}
                                                                        searchable={false}
                                                                        disabled={false}
                                                                        clearable={false}
                                                                        placeholder='1'
                                                                        onChange={(e) => this.onChildAgeChange(index, index1, e)}
                                                                        isSortByAlphabet={false}
                                                                    />
                                                                </div>
                                                            );
                                                        })
                                                        }
                                                    </div>
                                                </div>
                                                <div className={fact.disableDiv ? 'jp-divdisplay-block-2' : 'jp-divdisplay'}>
                                                    <div className=' pex-room-title'>
                                                        <div className='collapsemaindiv'>
                                                            <p className='collapsetitile'>{fact.adult} Adult, {fact.children} Children</p>
                                                            <div className='buttontotheright'>
                                                                <button className='editbtn' onClick={() => this.enableDiv(index)} onKeyDown={(event) => this.handleKeyEsc(event)} tabIndex='0' aria-label='edit room'>Edit</button>
                                                                <button onClick={() => this.removeRooms(index)} onKeyDown={(event) => this.handleKeyEsc(event)} className='removebtn' tabIndex='0' aria-label='remove room' >Remove</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>);
                                    })
                                }</div>
                            <div className='addmorebtn-block'>
                                <button className={this.state.buttoncolor ? 'jp-addmorebtn' : 'jp-addmorebtn1'} onClick={this.addRooms.bind(this)} tabIndex='0' aria-label={this.state.buttoncolor ? 'add more room' : 'add more room button disable'} > + Add more room</button>
                            </div>

                        </div>
                    )
                }
            </div>
        );
    }
}
export default DesktopPaxConfig;

DesktopPaxConfig.defaultProps = {
    defaultAdult: 2,
    defaultChild: 0,
    minAdult: 1,
    maxAdult: 6,
    minChild: 0,
    maxChild: 4,
    maximumRooms: 5,
    guestPerRooms: 6,
    totalPax: 9
};

DesktopPaxConfig.propTypes = {
    /** Label for displaying age range for adult */
    adultAgeRangeLabel: PropTypes.string,
    /** Label for displaying age range for childern */
    childAgeRangeLabel: PropTypes.string,
    /** Default number of adult */
    defaultAdult: PropTypes.number,
    /** Default number of child */
    defaultChild: PropTypes.number,
    /** Minimum number of child */
    minChild: PropTypes.number,
    /** total number of pax allowed */
    totalPax: PropTypes.number,
    /** maximum adults allowed */
    maxAdult: PropTypes.number,
    /** minimum adults allowed */
    minAdult: PropTypes.number,
    /** maximum child allowed */
    maxChild: PropTypes.number,
    /** maximum rooms can be booked */
    maximumRooms: PropTypes.number,
    /** number of guest allowed per room  */
    guestPerRooms: PropTypes.number,
    /** function to set values */
    onBlurPaxConfigText: PropTypes.func,
    /** Array of child age */
    paxAgeOptions: PropTypes.array
};