import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';
import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  List,
  ListItem,
  Divider,
  Snackbar,
  Tabs, Tab,
  RaisedButton,
  Toolbar,
  DatePicker,
  FontIcon,
  MenuItem,
  Toggle,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  RadioButton,
  TextField,
  Paper,
  RadioButtonGroup,
  Avatar,
} from 'material-ui';
import {Icon, Button, notification, Table, Tooltip as TooltipAntd} from 'antd';
import {yellow500} from 'material-ui/styles/colors';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import SwipeableViews from 'react-swipeable-views';
import SearchIcon from 'material-ui/svg-icons/action/search';
import AddIcon from 'material-ui/svg-icons/content/add';
import DeleteIcon from 'material-ui/svg-icons/action/delete';
import ImageEdit from 'material-ui/svg-icons/image/edit';
import ActionHome from 'material-ui/svg-icons/action/home';
import EmptyComponent from '../../EmptyComponent';
import {Link} from 'react-router-dom';
import {LINKS} from "../../../routes";
import './style.scss';
import {appConfig} from "../../../config/app";
import NumberFormat from 'react-number-format';
import LoadingDialog from "../../LoadingDialog";
import Loader from 'react-loader-advanced';
import {omit} from 'lodash';

@inject('appstate')
@observer
export default class ProfileComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      formData: {
        user_store_id:'',
        name: '',
        tagline:'',
        description: '',
        image: '',
      },
      my_item: 0,
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.myStore = props.appstate.myStore;
    this.myStoreItem = props.appstate.myStoreItem;
    this.userData = props.appstate.userData;
    this.globalUI = props.appstate.globalUI;
  }

  componentDidMount() {
    if(this.userData.role == 'store') {
      this.myStore.getAll()
        .then(res => {
          this.setState({
            formData: {
              ...this.myStore.data
            }
          });
          this.myStoreItem.getAll().then(res => {
            this.setState({
              my_item: res.max
            });
          })
        });
    }
    else if(this.userData.role == 'administrator') {
      this.myStore.setRequestQuery({user_store_id : this.props.id});
      this.myStoreItem.setRequestQuery({user_store_id : this.props.id});
      this.myStore.getAll()
        .then(res => {
          this.setState({
            formData: {
              ...this.myStore.data
            }
          });
          this.myStoreItem.getAll().then(res => {
            this.setState({
              my_item: res.max
            });
          })
        });
    }
  }

  changePicture = async (event, index, value) => {
    if(this.userData.role == 'administrator') {
      this.setState({
        user_store_id:this.props.id
      });
      console.log(this.state.user_store_id);
    }
    let data = this.state.formData;

    const file = event.nativeEvent.target.files[0];
    const allowedFile = ['jpg', 'jpeg', 'png', 'gif'];

    const [ext] = file.name.split('.').reverse();

    if (!allowedFile.includes(ext.toLowerCase())) {

    }

    let response = await this.http.upload(file);
    data.image = response.path;
    this.setState({
      formData: data
    });
    await this.save();
    // console.log(event.nativeEvent);
  };

  save = () => {
    // console.log(this.props.id, this.state.formData);
    // return;
    if(this.userData.role == 'administrator') {
      this.setState({
        formData : {
          ...this.state.formData,
          user_store_id : this.props.id
        }
      },() => this.myStore.update(this.props.id, omit(this.state.formData,['user_store_id'])).then(res => {
        this.globalUI.openSnackbar('Your Store has been succesfully updated');
      }))
    }
    else if(this.userData.role == 'store'){
      this.myStore.update(this.state.formData.id, this.state.formData).then(res => {
        this.globalUI.openSnackbar('Your Store has been succesfully updated');
      })
    }

  }

  render() {

    const styles = {
      button: {
        margin: 12,
      },
      exampleImageInput: {
        cursor: 'pointer',
        position: 'absolute',
        top: 0,
        bottom: 0,
        right: 0,
        left: 0,
        width: '100%',
        opacity: 0,
      },
    };

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

    return (
      <div className="row">
        <div className="col l12 m12 s12">
          <Card className="animated fadeIn marketplace-cardLite">
            <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
              <ToolbarGroup>
                <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={'Store Profile'}/>
              </ToolbarGroup>
              {/* <ToolbarGroup className="ToolbarGroupLast">
                <ToolbarSeparator/>
                <Link to={LINKS.USER}>
                  <RaisedButton className="ToolbarGroupLastButton" icon={<AddIcon/>} label="New User" primary={true}/>
                </Link>
              </ToolbarGroup> */}
            </Toolbar>
            <Divider/>
            <div style={{padding: 15}}>
              <div className="row">
                <div className="col s12 m12 l5">
                  <Card className='marketplace-cardLite-light'>
                    <CardMedia
                      overlayContentStyle={{background: 'transparent'}}
                      overlay={
                        <div className='row'>
                          <div className="flex">
                            <div className="picture-container">
                              <img
                                src={(this.state.formData.image !== null || '') ? this.http.appendImagePath(this.state.formData.image) : '/assets/images/icon/icon-store24x.jpg'}
                                className="store-picture"/>
                              <div className="middle">
                                <div className="store-text text">
                                  <ImageEdit color='#fff'/>
                                </div>
                              </div>
                              <input type="file" onChange={this.changePicture} accept="image/*"  style={styles.exampleImageInput}/>
                            </div>
                            <div>
                              <div className='store-name'>{this.myStore.data.name}</div>
                              <div className='store-join'>{this.myStore.data.tagline}</div>
                            </div>
                          </div>
                          <svg className="decor" width="842px" height="219px" viewBox="0 0 842 219"
                               preserveAspectRatio="xMaxYMax meet" version="1.1"
                               xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/1999/xlink">
                            <g transform="translate(-381.000000, -362.000000)" fill="#FFFFFF">
                              <path className="decor-path"
                                    d="M1223,362 L1223,581 L381,581 C868.912802,575.666667 1149.57947,502.666667 1223,362 Z"></path>
                            </g>
                          </svg>
                        </div>
                      }
                    >
                      <div className="banner-container">
                        <img
                          src="https://images.unsplash.com/photo-1502160348486-995f41fa55b1?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=199db34d62d362d0073043ac931c6f4e&auto=format&fit=crop&w=750&q=80 750w"
                          className="store-banner" alt=""/>
                      </div>
                    </CardMedia>
                    <CardText className="no-padding mt-20">
                      {/*<Divider/>*/}
                      {/*<div className='row' style={{paddingTop: 15, paddingBottom: -5}}>*/}
                      {/*<a href="#">*/}
                      {/*<div className='col s6' style={{marginTop: 7, color: '#777'}}>*/}
                      {/*Visit My Store*/}
                      {/*</div>*/}
                      {/*<div className='col s6' style={{textAlign: 'right'}}>*/}
                      {/*<Avatar size='25' icon={<i className="material-icons">computer</i>}/>*/}
                      {/*</div>*/}
                      {/*</a>*/}
                      {/*</div>*/}
                      <div className='row marketplace-row-profile-info'>
                        <Link to={LINKS.ITEMS}>
                          <div className='col s1' style={{textAlign: 'left', paddingTop: 3}}>
                            <Avatar size={25} icon={<i className="material-icons">business_center</i>}/>
                          </div>
                          <div className='col s8' style={{marginTop: 7, color: '#777'}}>
                            My Items
                          </div>
                          <div className='col s3 btn-product'
                               style={{textAlign: 'right', paddingTop: 6}}>
                            <Link to={LINKS.ITEMS}>{my_item} </Link><Icon className="ml-8" type="right"/>
                          </div>
                        </Link>
                      </div>
                      {/*<div className='row marketplace-row-profile-info'>*/}
                        {/*<div className='col s1' style={{textAlign: 'left', paddingTop: 3}}>*/}
                          {/*<Avatar size={25} icon={<i className="material-icons">chat</i>}/>*/}
                        {/*</div>*/}
                        {/*<div className='col s8' style={{marginTop: 7, color: '#777'}}>*/}
                          {/*Reply Chat Percentage*/}
                        {/*</div>*/}
                        {/*<div className='col s3' style={{textAlign: 'right', color: '#000', paddingTop: 6}}>*/}
                          {/*0%*/}
                        {/*</div>*/}
                      {/*</div>*/}
                      {/*<div className='row marketplace-row-profile-info'>*/}
                        {/*<div className='col s1' style={{textAlign: 'left', paddingTop: 3}}>*/}
                          {/*<Avatar size={25} icon={<i className="material-icons">access_time</i>}/>*/}
                        {/*</div>*/}
                        {/*<div className='col s8' style={{marginTop: 7, color: '#777'}}>*/}
                          {/*Chat Time Replied*/}
                        {/*</div>*/}
                        {/*<div className='col s3' style={{textAlign: 'right', color: '#5cb85c', paddingTop: 6}}>*/}
                          {/*In Minutes*/}
                        {/*</div>*/}
                      {/*</div>*/}
                      {/*<div className='row marketplace-row-profile-info'>*/}
                        {/*<a href="#">*/}
                          {/*<div className='col s1' style={{textAlign: 'left', paddingTop: 3}}>*/}
                            {/*<Avatar size={25} icon={<i className="material-icons">star_border</i>}/>*/}
                          {/*</div>*/}
                          {/*<div className='col s8' style={{marginTop: 7, color: '#777'}}>*/}
                            {/*Customer's Rating*/}
                          {/*</div>*/}
                          {/*<div className='col s3 btn-product'*/}
                               {/*style={{textAlign: 'right', color: '#6772e5', paddingTop: 6}}>*/}
                            {/*0 <Icon className="ml-8" type="right"/>*/}
                          {/*</div>*/}
                        {/*</a>*/}
                      {/*</div>*/}
                      {/*<div className='row marketplace-row-profile-info'>*/}
                        {/*<a href="#">*/}
                          {/*<div className='col s1' style={{textAlign: 'left', paddingTop: 3}}>*/}
                            {/*<Avatar size={25} icon={<i className="material-icons">money_off</i>}/>*/}
                          {/*</div>*/}
                          {/*<div className='col s8' style={{marginTop: 7, color: '#777'}}>*/}
                            {/*Total Cancellation / Refund*/}
                          {/*</div>*/}
                          {/*<div className='col s3 btn-product'*/}
                               {/*style={{textAlign: 'right', color: '#6772e5', paddingTop: 6}}>*/}
                            {/*0 <Icon className="ml-8" type="right"/>*/}
                          {/*</div>*/}
                        {/*</a>*/}
                      {/*</div>*/}
                    </CardText>
                  </Card>
                </div>
                <div className="col s12 m12 l7">
                  <div style={{padding: 15}}>
                    <div className="row">
                      <div className="col s12">
                        <p className="label-form">Store Name</p>
                        {wrapperText("name")(
                          <TextField
                            hintText="E.g. Aby Store"
                            fullWidth={true}
                            className="font-14"
                          />
                        )}
                      </div>
                    </div>
                    <div className="row">
                      <div className="col s12">
                        <p className="label-form">Store Tagline</p>
                        {wrapperText("tagline")(
                          <TextField
                            hintText="E.g. Aby Store"
                            fullWidth={true}
                            className="font-14"
                          />
                        )}
                      </div>
                    </div>
                    <div className="row">
                      <div className="col s12">
                        <p className="label-form">Store Description</p>
                        {wrapperText("description")(
                          <TextField
                            hintText="Tell Anything about your store"
                            fullWidth={true}
                            className="font-14"
                          />
                        )}
                      </div>
                    </div>
                    <div className="row">
                      <div className='col s12 m12 l12' style={{textAlign: "right"}}>
                        <RaisedButton
                          label="Save"
                          onClick={() => this.save()}
                          primary={true}
                          style={{marginTop: '2.3em'}}/>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    );
  }
}
