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 schema from 'async-validator'
import startCase from 'lodash.startcase';
import moment from 'moment';
import get from 'lodash.get';

@inject('appstate')
@observer
export default class CategoryData extends React.Component {

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

    this.http = props.appstate.http;    
  }

  // componentWillUnmount(){
    
  // }

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

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

    if(defaultValue.image.icon != ""){
      let file = defaultValue.image.icon.split("/");
      this.setState({
        fileList : [{
          uid: file[2],
          name: file[2],
          status: 'done',
          url: this.http.appendImagePath(defaultValue.image.icon),
          path: defaultValue.image.icon,
          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));
      })
      
  }
  
  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);
    // if (this.state.onChangeTimeoutId) {
    //   this.setState({
    //     onChangeTimeoutId: false
    //   });
    //   return clearTimeout(this.state.onChangeTimeoutId);
    // }

    // const onChangeTimeoutId = setTimeout(() => {
    //   if (this.props.onChangeData && typeof this.props.onChangeData === 'function') {
    //     this.props.onChangeData(this.state.formData);
    //   }

    //   this.setState({
    //     onChangeTimeoutId: false
    //   });

    // }, 322);

    // this.setState({onChangeTimeoutId});
  }

  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;

    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">Icon</p>
              <Upload
                listType="picture-card"
                fileList={fileList}
                customRequest={(...args) => this.uploaderHandlerIcon(...args)}
                style={{}}
                onChange={this.handleChange}
              >
                {fileList.length == 1 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          </div>
          <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>

      </div>
    );

  }

}
