import React from 'react';
import {inject, observer} from 'mobx-react';
import {DatePicker, MenuItem, SelectField, TextField, Checkbox,
  AutoComplete, } 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';
import NumberFormat from 'react-number-format';

const InputGroup = Input.Group;
const { TextArea } = Input;

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

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      type:1,
      dataSource: [],
      formData: Object.assign({
        type:'',
        value_id:null,
        image:'',
        link_target:''
      },props.defaultValue ) || {},
      checked: true,
      errorText: {},
      onChangeTimeoutId: false,
      previewVisible : '',
      previewImage : '',
      fileList : '',
      previewVisibleBackground : '',
      previewImageBackground : '',
      fileListBackground : '',
    };
    this.item = props.appstate.item;
    this.http = props.appstate.http;
    this.featured = props.appstate.featuredClass;
  }

  // componentWillUnmount(){

  // }

  async componentDidMount() {
    const {defaultValue={},mode} = this.props;
    await this.item.getAll();
    // this.setState({
    //   formData : this.featured.formData
    // },()=>this.triggerOnChange(2));


    // if(mode == "update"){
    //   await this.featured.getDetail(this.props.defaultValue.id)
    // }

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



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

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

  handleChangeType = (event, index, value) => {
    this.setState({
      formData : {
        ...this.state.formData,
        type:value
      }
    })
  };

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

    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 wrapperAutocomplete = key => ele => React.cloneElement(ele, {
      value : this.state.formData[key],
      onNewRequest: (v) => {
        this.setState({
          formData: {
            ...this.state.formData,
            [key]: v.id,
          }
        }, () => this.triggerOnChange(key));
      }
    });

    const {mode="create"} = this.props;
    const dataSourceConfig = {
      text: 'name',
      value: 'id',
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return(
      <div style={{marginTop: 10}}>
        <div className={"row"}>
          <div className={"col s12"}>
            <p className="label-form">Choose Type Banner</p>
            {wrapperSelect("type")(
            <SelectField
              //value={this.state.formData.type}
              //onChange={this.handleChangeType}
            >
              <MenuItem value={'items'} primaryText="Item" />
              <MenuItem value={'link'} primaryText="Banner" />
            </SelectField>)}
          </div>
        </div>

        <div className={"row"}>
          {(this.state.formData.type === "items") ? (
            <div className={"col s12"}>
              <div>
                <p className="label-form">Item Name</p>
                {wrapperAutocomplete("value_id")(
                  <AutoComplete
                    hintText="E.g. T-Shirt"
                    dataSource={this.item.data.slice()}
                    filter={AutoComplete.fuzzyFilter}
                    dataSourceConfig={dataSourceConfig}
                    openOnFocus={true}
                    fullWidth={true}
                  />
                )}
              </div>
            </div>
            ) : ""}

          { (this.state.formData.type === "link") ?
            (
              <div>
                <div className={"col s12 m6 l6"}>
                  <p className="label-form" onClick={()=>console.log(this.state.formData)}>Banner</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 className={"col s12 m6 l6"}>
                  <p className="label-form">Hyperlink (optional)</p>
                  {wrapperText("link_target")(
                    <TextField
                      fullWidth={true}
                      hintText="Link target, use http:// or https://"/>
                  )}
                </div>
              </div>
            ) : ""
          }

        </div>

      </div>
    );

  }

}
