import React from 'react';
import {inject, observer} from 'mobx-react';
import {DatePicker, MenuItem, SelectField, TextField, Checkbox, } from 'material-ui';
import { Upload, Icon, Modal, Input, Select, Switch, message, Button as ButtonAntd } from 'antd';
import { ChromePicker } from 'react-color'
import reactCSS from 'reactcss'
@inject('appstate')
@observer
export default class CategoryData extends React.Component {

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
        formData: Object.assign({
          name : '',
          color : '',
          background_image : ''
        },props.defaultValue ) || {},
        checked: true,
        errorText: {},
        onChangeTimeoutId: false,
        countries: [],
        previewVisible : '', 
        previewImage : '', 
        fileList : '',
        previewVisibleBackground : false,
        previewImageBackground : '', 
        fileListBackground : '',
      displayColorPicker : false
    };

    this.http = props.appstate.http;    
  }

  // componentWillUnmount(){
    
  // }

  componentDidMount() {
    const {defaultValue={}} = this.props;
    console.log(defaultValue,'thissssss')
    this.setState({
      formData : {
        ...this.state.formData,
        ...defaultValue
      }
    })

    if(this.props.mode == 'update'){
    if(defaultValue.background_image != ""){
      let file = defaultValue.background_image.split("/");
      this.setState({
        fileListBackground : [{
          uid: file[2],
          name: file[2],
          status: 'done',
          url: this.http.appendImagePath(defaultValue.background_image),
          path: defaultValue.background_image,
          type: 'main'
        }]
      })
    }
  }

  }
  handleCancelBackground = () => this.setState({ previewVisibleBackground: false });
  handleChangeBackground = ({ fileList }) => {
    this.setState({ fileListBackground : fileList }); 
    console.log(fileList, 'remove')
    if(fileList.length == 0){
      this.setState({
        formData : {
          ...this.state.formData,
          background_image : ''
        }
      },()=>this.triggerOnChange(2))
    }
  };

  uploaderHandlerBackground({file, onProgress}) {
    this.http.upload(file)
      .then(res => {
        const {fileListBackground} = this.state;
        let newFileList = fileListBackground.filter((obj)=>{
          if(!obj.lastModified){
            return true;
          }

        })
        newFileList.push({
          uid: newFileList.length,
          name: file.name,
          status: 'done',
          url: this.http.appendImagePath(res.path),
          path: res.path,
          type: 'main'
        });

        this.setState({
          fileListBackground : newFileList,
          formData : {
            ...this.state.formData,
            background_image : res.path
          }
        }, () => this.triggerOnChange(2));
      })
      
  }

  handleClickColor = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker })
  };

  handleCloseColor = () => {
    this.setState({ displayColorPicker: false })
  };

  handleChangeCompleteColor = (color, event) => {
    this.setState({
      formData : {
        ...this.state.formData,
        color:color.hex
        // icon : ''
      },
      color : color.rgb
    },()=>this.triggerOnChange(2))

    console.log(color);
  };


  handleCancel = () => this.setState({ previewVisible: false });
  handleChange = ({ fileList }) => {
    this.setState({ fileList }); 
    console.log(fileList, 'remove')
    if(fileList.length == 0){
      this.setState({
        formData : {
          ...this.state.formData,
          icon : ''
        }
      },()=>this.triggerOnChange(2))
    }
  };
  uploaderHandlerIcon({file, onProgress}) {
    this.http.upload(file)
      .then(res => {
        const {fileList} = this.state;
        let newFileList = fileList.filter((obj)=>{
          if(!obj.lastModified){
            return true;
          }

        })
        newFileList.push({
          uid: newFileList.length,
          name: file.name,
          status: 'done',
          url: this.http.appendImagePath(res.path),
          path: res.path,
          type: 'main'
        });
        this.setState({
          fileList : newFileList,
          formData : {
            ...this.state.formData,
            icon : res.path
          }
        }, () => this.triggerOnChange(2));
      })
      
  }

  triggerOnChange(key) {
    this.props.onChangeData(this.state.formData);
  }

  updateCheck() {
    this.setState((oldState) => {
      return {
        checked: !oldState.checked,
      };
    });
  }

  render() {
    const { previewVisible, previewImage, fileList,previewVisibleBackground, previewImageBackground, fileListBackground } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    const wrapperText = key => ele => React.cloneElement(ele, {
      value: this.state.formData[key],
      errorText: this.state.errorText[key],
  	  onChange: (e) => {
  	    this.setState({
          formData: {
            ...this.state.formData,
            [key]: e.target.value,
          }
        }, () => this.triggerOnChange(key));
      }
    });

    const wrapperSelect = key => ele => React.cloneElement(ele, {
      value: this.state.formData[key],
      errorText: this.state.errorText[key],
      onChange: (e, k, v) => {
        this.setState({
          formData: {
            ...this.state.formData,
            [key]: v,
          }
        }, () => this.triggerOnChange(key));
      }
    });

    const wrapperSwitch = key => ele => React.cloneElement(ele, {
      checked: this.state.formData[key],
      errorText: this.state.errorText[key],
      onCheck: (e, v) => {
        this.setState({
          formData: {
            ...this.state.formData,
            [key]: v,
          }
        }, () => this.triggerOnChange(key));
      }
    });

    const {mode="create"} = this.props;
    const styles = reactCSS({
      'default': {
        color: {
          width: '64px',
          height: '28px',
          borderRadius: '2px',
          background: this.state.formData.color
        },
        swatch: {
          padding: '5px',
          background: '#fff',
          borderRadius: '1px',
          boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
          display: 'inline-block',
          cursor: 'pointer',
        },
        popover: {
          position: 'absolute',
          zIndex: '2',
        },
        cover: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
        },
      },
    });

    return(
      <div style={{
        paddingTop: 10
      }}>

        <div className="row">

          <div className="col s12 m12 l12">
            <div>
              <p className="label-form">Name</p>
              {wrapperText("name")(
                <TextField
                fullWidth={true}
                hintText="E.g. Sport"/>
              )}
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col s12 m6 l6">
            <div>
              <p className="label-form" onClick={()=>console.log(this.state.formData)}>Background Image</p>
              <Upload
                listType="picture-card"
                fileList={fileListBackground}
                customRequest={(...args) => this.uploaderHandlerBackground(...args)}
                style={{}}
                onChange={this.handleChangeBackground}
              >
                {fileListBackground.length == 1 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisibleBackground} footer={null} onCancel={this.handleCancelBackground}>
                <img alt="example" style={{ width: '100%' }} src={previewImageBackground} />
              </Modal>
            </div>
          </div>

          <div className="col s12 m6 l6">
            <div>
              <p className="label-form">Color</p>
              <div style={ styles.swatch } onClick={ this.handleClickColor }>
                <div style={ styles.color } />
              </div>
              { this.state.displayColorPicker && <div style={ styles.popover }>
                <div style={ styles.cover } onClick={ this.handleCloseColor }/>
                <ChromePicker color={ this.state.formData.color } onChangeComplete={this.handleChangeCompleteColor} />
              </div>}

            </div>
          </div>

        </div>

      </div>
    );

  }

}
