import React from "react";
import { connect } from "react-redux";
//import { switchAccount } from "../../../actions";

class Company extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			company: {}, 
			opened: false, 
			companies: null, 
		}
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		return {
			company: nextProps.company, 
			companies: nextProps.companies, 
		};
	}

	_handleOnClick = () => 
	{
		const { companies, opened } = this.state;
		if(companies !== null && companies.length > 1)
		{
			this.setState({ opened: !opened ? true : false })	
		}
	}

	_handle_onSelectCompany = (acc_number) => 
	{
		this.props.router.push(`/switch/?account=${ acc_number }`);
	}

	render()
	{
		const { company, companies, opened } = this.state;

		return (
			<div className="right company-dropdown" onClick={ this._handleOnClick }>
				<p align="right" className={ companies !== null && companies.length > 1 ? "arrow" : "" }>{/*  className="arrow" */}
					<b>{ company.title }</b><br/>
					{company.inn != null && <span>ИНН: { company.inn } </span>}
					{company.kpp != null && <span>КПП: { company.kpp }</span>}
				</p>
				<div className={`companies_list ${ opened && "opened" }`}> {/* opened */}
					{ companies !== null && companies.map((entry, index) => (
						<div key={ index } className={ `company_item ${ company.active === entry.acc_number && "selected" }` } onClick={ () => this._handle_onSelectCompany(entry.acc_number) }>
							<p align="right">
								<b>{ entry.title }</b><br/>
								ИНН: <span>{ entry.inn }</span> { entry.kpp !== '' && (<>КПП: <span>{ entry.kpp }</span></>) }
							</p>
						</div>
					)) }
				</div>
			</div>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		company: state.company, 
		companies: state.companies.list, 
	}
}

export default connect(mapStateToProps)(Company);