import React from 'react';
import PropTypes from 'prop-types';
import defaults from 'lodash/defaults';

import { TabbedSelect, MultiSelectValue } from '@nestio/pam';
import { renderMultiSelectValueLabelWithPlaceHolder } from './InputSelect';

const groupSortOrder = ['Manhattan','Brooklyn','Bronx','Queens','Staten Island'];

export default class NeighborhoodsSelect extends React.Component {
    _group(neighborhood) {
        // TODO rather than having this logic here,
        // the group should really just come though the API
        if(['NJ','CT'].indexOf(neighborhood.state) != -1 && neighborhood.area != 'None') {
            return neighborhood.area;
        }
        return neighborhood.city;
    }

    _groupCompare(a, b) {
        // Lookup the group in a sort order array
        // if it's ot present, give a really high value,
        // so it sorts to the end of the list

        let aIdx = groupSortOrder.indexOf(a);
        let bIdx = groupSortOrder.indexOf(b);
        aIdx = (aIdx != -1) ? aIdx : 1000;
        bIdx = (bIdx != -1) ? bIdx : 1000;

        if(aIdx === bIdx) {
            // If they're the same, sort by name
            return a.localeCompare(b);
        }
        return aIdx - bIdx;
    }

    _groupNeighborhoods() {
        const tabbedOpts = {};
        this.props.options.forEach((n) => {
            const group = this._group(n);
            defaults(tabbedOpts, { [group]: [] });
            tabbedOpts[group].push({ label: n.name, value: n.id });
        });

        const groups = Object.keys(tabbedOpts).sort(this._groupCompare);
        return groups.map((group) => {
            return { name: group, choices: tabbedOpts[group].sort((a, b) => {
                return a.label.localeCompare(b.label);
            }) };
        });

    }

    render() {
        // TODO if only a handful of neighborhoods, turn into a dropdown?
        // TODO only do this when neighborhoods are actually updated?
        const groups = this._groupNeighborhoods();
        // TODO Show something while loading
        return (
            <TabbedSelect
                menuLabel="Neighborhoods"
                value={this.props.value}
                valueLabel="Neighborhoods"
                options={groups}
                onChange={this.props.onChange}
                onClose={this.props.onClose}
                ValueComponent={props => {
                    return (
                        <MultiSelectValue
                            {...props}
                            renderValueLabel={renderMultiSelectValueLabelWithPlaceHolder(props.placeholder)}
                        />
                    );
                }}
            />
        );
    }
}

NeighborhoodsSelect.propTypes = {
    options: PropTypes.array,
    inputName: PropTypes.string,
    value: PropTypes.array,
    onClose: PropTypes.func,
    onChange: PropTypes.func
};
