import React from 'react'
import styled from 'styled-components';
import PropTypes from 'prop-types';

const Styles = styled.div`${({isOpen})=>`
	.rivigo-accordion-body{
		height : 0px;
	    overflow: hidden;
	    transition: height 0.5s ease;
	}
`}`

export default class Accordion extends React.Component{
	constructor(){
		super()
		this.state = { isOpen : false }
	}

	toggleState = () => {
		this.body.style.height = this.state.isOpen ? '0px' : this.body.scrollHeight+'px'
		if(!this.state.isOpen){
			setTimeout(()=>{
				this.body.style.overflow = 'visible'
			},500)
		}
		else {
			this.body.style.overflow = 'hidden'
		}
		this.setState({ isOpen : !this.state.isOpen })
	}

	bodyRef = el => {
		if(el){
			this.body = el
		}
	}

	render(){
		return(
			<Styles isOpen={this.state.isOpen}>
				{this.props.renderBase(this.toggleState,this.state.isOpen)}
				<div ref={this.bodyRef} key='rivigo-accordion-body' className='rivigo-accordion-body'>
					{this.props.renderBody(this.toggleState,this.state.isOpen)}
				</div>
			</Styles>
		)
	}

	componentDidUpdate(){
		if(this.state.isOpen) {
			this.body.style.height=this.body.firstChild.scrollHeight+'px'
		}
	}
}

