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,Popover } 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';
import {featherIconLists} from "./icons";

// as MCIcons from 'react-native-vector-icons/glyphmaps/MaterialCommunityIcons.json';
import FeatherIcon from 'feather-icons-react';
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 = {
      dataSource: [],
      formData: Object.assign({
        name : '',
        url : '',
        icon : '',
        type : 'url'
      },props.defaultValue ) || {},
      checked: true,
      errorText: {},
      icon_search : '',
      tag_search : '',
      onChangeTimeoutId: false,
    
    };
    this.http = props.appstate.http;
    this.customMenu = props.appstate.custom_menu;
    this.tags = props.appstate.tags;
  }

  // componentWillUnmount(){

  // }

  async componentDidMount() {
    const {defaultValue={},mode} = this.props;

    await this.tags.getAll();

    this.setState({
      formData : Object.assign(defaultValue,this.state.formData,
        {
          tag : get(defaultValue,'additional_data.tag_id',false) ? defaultValue.additional_data.tag_id : null,
          post_template : get(defaultValue,'additional_data.template',false) ? defaultValue.additional_data.template : null
        }),
      icon_search : defaultValue.icon,
      tag_search : get(defaultValue,'additional_data.tag_id',false)  ? this.tags.data.find(it=>it.id === defaultValue.additional_data.tag_id).name : ""
    },()=>this.triggerOnChange(2));

    
    let icons = [];
    featherIconLists.map(it=>{
      let _name = it;
      let _val = <MenuItem primaryText={_name} leftIcon={ <FeatherIcon icon={it} size="48"/>}/>
      icons.push({text:_name, value:(_val), valueKey:it});
    });
    this.setState({
      dataSource : icons
    })
  }


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

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


  render() {

    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],
      searchText : this.state[`${key}_search`],
      onNewRequest: (v) => {
        this.setState({
          formData: {
            ...this.state.formData,
            [key]: (key == 'tag') ? v.id : v.valueKey,
          }
        }, () => this.triggerOnChange(key));
      }
    });

    const {mode="create"} = this.props;
    
    let popoverText = (
      <div>
        <p>We used <strong>material design icon</strong> for our icon.<br/>To view list of icon please visit <a href="https://materialdesignicons.com" target="_blank">https://materialdesignicons.com/</a> then search and select an icon you desire</p>
      </div>
    )

    return(
      <div style={{marginTop: 10}}>
        <div className={"row"}>
          <div className={"col s12"}>
            <div>
              <p className="label-form">Type</p>
              {wrapperSelect("type")(
                <SelectField>
                  <MenuItem value={'url'} primaryText="Url" />
                  <MenuItem value={'post'} primaryText="Post" />
                </SelectField>
              )}
            </div>
          </div>
        </div>
        <div className={"row"}>
          <div className={"col s12"}>
            <div>
              <p className="label-form">Name</p>
              {wrapperText("name")(
              <TextField
                hintText="E.g. Homepage"
                fullWidth={true}
              />
              )}
            </div>
          </div>
        </div>

        {
          (this.state.formData.type == 'url') && <div className={"row"}>
            <div className={"col s12"}>
              <div>
                <p className="label-form">URL</p>
                {wrapperText("url")(
                  <TextField
                    hintText="E.g. https://www.yournicewebsite.com"
                    fullWidth={true}
                  />
                )}
              </div>
            </div>
          </div>

        }
        {
          (this.state.formData.type == 'post') &&
            <div>
              <div className={"row"}>
                <div className={"col s6"}>
                  <div>
                    <p className="label-form">Post Category</p>
                    {/*{wrapperAutocomplete("tag")(*/}
                      {/*<AutoComplete*/}
                        {/*hintText="E.g. Face, People"*/}
                        {/*dataSource={this.tags.data}*/}
                        {/*filter={AutoComplete.fuzzyFilter}*/}
                        {/*dataSourceConfig={{text : 'name',value:'id'}}*/}
                        {/*onUpdateInput={(val)=>this.setState({tag_search :val})}*/}
                        {/*maxSearchResults={5}*/}
                        {/*openOnFocus={true}*/}
                        {/*fullWidth={true}*/}
                      {/*/>*/}
                    {/*)}*/}
                    {wrapperSelect("tag")(
                      <SelectField>
                        {
                          this.tags.data.map(it=>(
                            <MenuItem value={it.id} primaryText={it.name}/>
                          ))
                        }
                      </SelectField>
                    )}
                  </div>
                </div>
                <div className={"col s6"}>
                  <div>
                    <p className="label-form">Post Template</p>
                    {wrapperSelect("post_template")(
                      <SelectField>
                        <MenuItem value={'template1'} primaryText="Template Full Card" />
                        <MenuItem value={'template2'} primaryText="Template Standart List" />
                      </SelectField>
                    )}
                  </div>
                </div>
              </div>
            </div>
        }

        <div className={"row"}>
          <div className={"col s6"}>
            <div>
              <p className="label-form">Icon <Popover content={popoverText} title="Icons"><Icon type="info-circle"/></Popover></p>
              {wrapperAutocomplete("icon")(
              <AutoComplete
                hintText="E.g. Face, People"
                dataSource={this.state.dataSource}
                // filter={(searchText,key)=>{
                //   console.log(searchText,typeof searchText, key, typeof key);
                //   return true;
                // }}
                filter={AutoComplete.caseInsensitiveFilter}
                dataSourceConfig={{text : 'text',value:'valueKey'}}
                onUpdateInput={(val)=>this.setState({icon_search :val})}
                maxSearchResults={20}
                listStyle={{ maxHeight: 200, overflow: 'auto' }}
                openOnFocus={true}
                fullWidth={true}
              />
              )}
            </div>
          </div>
          <div className={"col s6"}>
            {
              // (this.state.formData.icon !== '') && <i className={`mdi mdi-${this.state.formData.icon}`} style={{fontSize:'50pt'}}></i>
              (this.state.formData.icon !== '') && <FeatherIcon icon={this.state.formData.icon} size="48"/>
            }
          </div>
        </div>

        <div className={"row"}>
          <div className={"col s6"}>
            <div>
              <p className="label-form">Order</p>
              {wrapperText("order")(
                <TextField
                  hintText="Custom menu appearance order"
                  type={"number"}
                  fullWidth={true}
                />
              )}`
            </div>
          </div>
        </div>

      </div>
    );

  }

}
