import * as React from 'react';
import { ImageControlsProps } from '../types/controls';
import * as ReactDOM from 'react-dom';
import AddCircleRounded from '@material-ui/icons/AddCircleRounded';
import { ImageUpload } from 'ory-editor-ui';

class ImageDefaultControls extends React.Component<ImageControlsProps> {
  constructor(props){
    super(props);
    this.state = {
      imageList : [ 
        { 
          src : '',
          id : Math.floor(Math.random()*90000) + 10000,
          href : ''
        }
      ]
    }
    this.saveServerDataToState(props.state);
    this.addInputList = this.addInputList.bind(this);
  } 

  componentWillReceiveProps(nextProps) {
    if(nextProps.state && nextProps.state.carouselData && nextProps.state.carouselData.length > 0){
      const stateArr = nextProps.state.carouselData;
      console.log("[Carousel :: href componentwillreceiveprops] \n",this.state.imageList,"\n State array",stateArr)
      for(let i=0; i<this.state.imageList.length; i++) {
        if(this.state.imageList[i] && stateArr[i]) {
          this.state.imageList[i].src = stateArr[i].src;
          this.state.imageList[i].href = stateArr[i].href;
        }
      }   
    }
  }

  saveServerDataToState = (state) => {
    if(state.carouselData) {
      let tempImageArr = state.carouselData.map((item) => {
        return { 
            src : item.src,
            id : item.id,
            href : item.href
          }
      })
      this.state.imageList = tempImageArr;
    }
  } 

  handleChange = (e) => {
    if(this.props.handleChange) {
      this.props.handleChange(e);
    }  
  }   

  addInputList = ()=> {
    // if(this.state.imageList.length > 5 )
    //   return;

    if(this.state.imageList.length > 0 && this.state.imageList[this.state.imageList.length - 1].src === '')
      return;
    
    let tempObj = {
      src : '',
      id : Math.floor(Math.random()*90000) + 10000,
      href : ''
    }
    let tempArr = [...this.state.imageList];
    tempArr.push(tempObj);
    this.setState({imageList:tempArr},()=>{
      console.log("[Carousel addinput list SETSTATE CALLBACK ]",this.state.imageList);
    });
  }

  deleteInputList = (index, key) => {
    let tempArr = this.state.imageList.filter((item,i)=>{
      return i!=index;
    })

    if(tempArr.length === 0) {
      tempArr[0] = { 
        src : '',
        id : Math.floor(Math.random()*90000) + 10000,
        href : ''
      }
    }
    
    this.setState({imageList:tempArr});   
    if(this.props.deleteImage) {
      this.props.deleteImage(key);
    }  
  }

  editInputList = (index,key) => {
    let tempArr = [...this.state.imageList];
    tempArr[index].src = '';
    tempArr[index].href = '';
    
    this.setState({imageList:tempArr});   
    if(this.props.editImage) {
      this.props.editImage(key);
    }  
  }

  renderImageInputList = () =>{
    const { imageUpload, handleImageLoaded, handleImageUploaded } = this.props;
    // console.log("[Carousel :: href imageDefaultControl Method ]",this.state.imageList[0]);
    return this.state.imageList.map((item, index) => (
      <div className="image-input-toolbox" >
        <div style={{ display:item.src?'flex':'none', alignItems: 'center', paddingBottom: '20px' }}>
          <img src={item.src} className="thumbnail" />
          <div className="image-edit">
            <button type="button" onClick={()=>this.editInputList(index, item.id)} > EDIT </button>
          </div>
          <div className="image-delete">
            <button type="button" onClick={()=>this.deleteInputList(index, item.id)} > DELETE </button>
          </div>
        </div>
        <div style={{ display:item.src?'none':'block' }}>
          <label className='webbuilder_input_label' htmlFor="" style={{textAlign:'left'}}>Carousel Image </label>         
          {imageUpload && (
            <ImageUpload
              imageUpload={imageUpload}
              imageLoaded={handleImageLoaded}
              imageUploaded={(resp)=>handleImageUploaded(resp,item.id)}
              style={{ width:'100%', backgroundColor:'#e9f6ff',boxShadow:'initial', border: '1px solid #0290ff', color: '#0290ff', height: '33px', lineHeight: '33px', padding: '0' }}
            /> 
          )}
          <label className='webbuilder_input_label' htmlFor="" style={{margin:0}}>OR </label>
          <label className='webbuilder_input_label' htmlFor="" style={{textAlign:'left',marginTop:0}}>Paste Image URL </label>          
          <input 
            type="text"
            placeholder="Image url here"
            name="src"
            id={item.id}
            style={{ flex: 1 }}
            value={item.src} 
            onChange={this.handleChange}
            className='webbuilder_input_box'
          /> 
        </div>
        
        <label className='webbuilder_input_label' htmlFor="" style={{textAlign:'left'}}>Call to Action </label>          
        <input 
          type="text"
          placeholder="Action url here"
          name="href"
          id={item.id}
          style={{ flex: 1 }}
          value={item.href ? item.href : ''}
          onChange={this.handleChange}
          className='webbuilder_input_box'
        /> 
      </div>
    )
    )
  }

  render() {
    const { Renderer, readOnly, focused, state} = this.props;
    const { imageList } = this.state;
    var controlerDom = (
      <div className='ory-prevent-blur' >
        <div>
          <div style={{borderBottom: '1px solid #e4e8ea' }} className="toolbox-border">
            {this.renderImageInputList()}
            {/* {imageList.length < 5 &&<AddCircleRounded onClick={this.addInputList} style={{fontSize:'28px',position: 'relative', right: '20px', top: '-13px', float: 'right'}} />} */}
            <AddCircleRounded onClick={this.addInputList} style={{fontSize:'28px',position: 'relative', right: '20px', top: '-13px', float: 'right'}} />
          </div> 
        </div>    
      </div>
    )
    if(!readOnly && focused && document.getElementById('propertiesTab')){
      {ReactDOM.render((controlerDom), document.getElementById('propertiesTab'));}
    }
    return (  
      <div>
        <Renderer {...this.props} imagePreview={this.props.imagePreview} />
      </div>
    );
  }
};

export default ImageDefaultControls;