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,
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
  MenuItem,
  Toggle,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  RadioButton,
  TextField,
  Paper,
  RadioButtonGroup
} from 'material-ui';
import {List as ListAntd, Avatar, Input} 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 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 moment from 'moment';
import {last,upperCase,get} from 'lodash';

@inject('appstate')
@observer
export default class ChatComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.chatStore = props.appstate.message;
    this.state = {
      chatName : (this.chatStore.activerooms === '') ? "Please select user to start chatting" : this.chatStore.activerooms.name
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.userData = props.appstate.userData;

  }

  componentWillMount() {
    this.chatStore.getRooms();
    console.log(this.userData,'USER DATA')
  }

  componentDidUpdate (){
    let rightThing = document.getElementById('rightContainer');
    if(rightThing){
      rightThing.scrollTop = rightThing.scrollHeight;
    }
  };

  componentWillUnmount(){
    this.chatStore.reset();
  }


  handleChange = (chatSelected) => {
    this.chatStore.setRooms(chatSelected);
    this.setState({chatName : chatSelected.name})
    this.props.history.push(LINKS.INBOX + '/chat?r=' + chatSelected.id);
    this.scrollToBottom();
  };

  sendMessage = () =>{
    this.chatStore.sendMessage();
  };

  getChatDate = (created_at)=>{
    let dayDiffrent = moment(created_at).diff(moment(),'days');
    if(dayDiffrent == 0){
      return moment(created_at).format('H:mm');  
    }
    else if(dayDiffrent == -1){
      return 'Yesterday'  
    }
    else if(dayDiffrent < -1 && dayDiffrent >= -6){
      return moment(created_at).format('ddd');
    }
    else if(dayDiffrent < -6){
      return moment(created_at).format('M/D/YY'); 
    }
  }

  render() {

    return (
      <div className="row no-margin">
        <div className="col l12 m12 s12 no-padding">
          <Card className="animated fadeIn cardLite">
            <div className='containerChat'>
              <div className="row no-margin containerChatInner">
                <div className="col s4 m4 l4 no-padding ">
                  <div className={'containerLeftListChat'}>
                    <Toolbar className="toolbarCard header-page-chat-sticky"
                             style={{backgroundColor: '#fff', borderBottom: '2px solid #ddd'}}>
                      <ToolbarGroup>
                        <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={'Chats'}/>
                      </ToolbarGroup>
                    </Toolbar>
                    <Divider/>
                    <div className={'containerLeftListChatInner'} style={{padding:'0px'}}>
                      <ListAntd
                        itemLayout="horizontal"
                        dataSource={this.chatStore.chatrooms}
                        renderItem={item => (
                          <ListAntd.Item key={item.id} className={(item.id == this.chatStore.activerooms.id) ? 'active_chat' : 'unactive_chat'} onClick={()=>this.handleChange(item)}>
                            <ListAntd.Item.Meta
                              avatar={<Avatar style={{ backgroundColor: '#1976D2' ,color:'#FFF'}}>{item.name ? upperCase(item.name.substring(0,1)) : '-'}</Avatar>}
                              title={<div style={{display:'flex',justifyContent:'space-between'}}><span style={{color : '#000'}}>{item.name}</span><p className="description_chat_p" style={{color:'#B7B7B7','fontSize':'11px'}}>{this.getChatDate(last(item.message).created_at)}</p></div>}
                              description={<div style={{textOverflow: 'ellipsis',display:'flex',justifyContent:'space-between'}}><p className="description_chat_p">{(item.message.length == 0 )? 'Message empty' : ((last(item.message).message_sender_user_id === this.userData.user_id) ? 'You : ' : '')+`${last(item.message).message}` }</p><span className="new_message_count" style={{visibility:((item.unread_message > 0)?'visible':'hidden')}}>{item.unread_message}</span></div>}
                            />
                          </ListAntd.Item>
                        )}
                      />
                    </div>
                  </div>
                </div>
                <div className="col s8 m8 l8 no-padding ">
                  {/*<ListAntd*/}
                  {/*itemLayout="horizontal"*/}
                  {/*dataSource={data}*/}
                  {/*renderItem={item => (*/}
                  {/*<ListAntd.Item>*/}
                  {/*<ListAntd.Item.Meta*/}
                  {/*avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"/>}*/}
                  {/*title={<a href="https://ant.design">{item.title}</a>}*/}
                  {/*description="Ant Design, a design language for background applications, is refined by Ant UED Team"*/}
                  {/*/>*/}
                  {/*</ListAntd.Item>*/}
                  {/*)}*/}
                  {/*/>*/}
                  <Toolbar className="toolbarCard header-page-chat-sticky"
                           style={{
                             backgroundColor: '#fff',
                             borderBottom: '2px solid #ddd',
                             borderLeft: '1px solid #ddd',
                             borderRadius: 0
                           }}>
                    <ToolbarGroup>
                      <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={this.state.chatName}/>
                    </ToolbarGroup>
                  </Toolbar>
                  <Divider/>
                  {this.chatStore.message.length > 0 ? (
                    <div>
                    <div className={'containerRightListChatInner'} id="rightContainer">
                      {this.chatStore.message.map((message,index)=>{
                        // if(moment(message.created_at).diff(moment(),'days') == 0){
                        //  return (<div className="chat-date-separator"><span>Today</span></div>)
                        // }
                        
                        
                        // else if(moment(message.created_at).diff(moment(),'days') == -1){
                        //   return  (<div className="chat-date-separator"><span>Yesterday</span></div>)
                        // }

                        if(message.yours_message == true || message.yours_message == "true"){
                          return (
                            <div className="chat-message self">
                              <div className="chat-message-content-w">
                                <div className="chat-message-content">{message.message}
                                </div>
                              </div>
                              <div className="chat-message-date">{moment(message.created_at).format('HH:mm')}</div>
                              <div className="chat-message-avatar"><img alt="" src="/assets/images/icon/icon-store24x.jpg"/></div>
                            </div>
                          )
                        }
                        else if(message.yours_message == false || message.yours_message == "false"){
                          return (
                            <div className={'chat-message'}>
                              <div className={'chat-message-content-w'}>
                                <div className={'messegesChat'}>{message.message}</div>
                              </div>
                              <Avatar style={{ backgroundColor: '#1976D2' ,color:'#FFF'}}>{message.user.email ? upperCase(message.user.email.substring(0,1)) : '-'}</Avatar>
                              <div className="chat-message-date">{moment(message.created_at).format('HH:mm')}</div>
                            </div>
                          )
                        }
                      })}


                      {/*<div className="chat-date-separator"><span>Yesterday</span></div>*/}

                      {/*<div className={'chat-message'}>*/}
                        {/*<div className={'chat-message-content-w'}>*/}
                          {/*<div className={'messegesChat'}>Hallo Admin.....</div>*/}
                        {/*</div>*/}
                        {/*<div className={'chat-message-avatar'}>*/}
                          {/*<img src="/assets/images/avatar3.jpg" alt=""/>*/}
                        {/*</div>*/}
                        {/*<div className="chat-message-date">9:12am</div>*/}
                      {/*</div>*/}

                      {/*<div className={'chat-message'}>*/}
                        {/*<div className={'chat-message-content-w'}>*/}
                          {/*<div className={'messegesChat'}>Slept train nearby a its is design size agreeable. And check*/}
                            {/*cons, but countries the was to such any founding company*/}
                          {/*</div>*/}
                        {/*</div>*/}
                        {/*<div className={'chat-message-avatar'}>*/}
                          {/*<img src="/assets/images/avatar3.jpg" alt=""/>*/}
                        {/*</div>*/}
                        {/*<div className="chat-message-date">9:12am</div>*/}
                      {/*</div>*/}

                      {/*<div className={'chat-message'}>*/}
                        {/*<div className={'chat-message-content-w'}>*/}
                          {/*<div className={'messegesChat'}>Slept train nearby a its is design size agreeable. And check*/}
                            {/*cons, but countries the was to such any founding company*/}
                          {/*</div>*/}
                        {/*</div>*/}
                        {/*<div className={'chat-message-avatar'}>*/}
                          {/*<img src="/assets/images/avatar3.jpg" alt=""/>*/}
                        {/*</div>*/}
                        {/*<div className="chat-message-date">9:12am</div>*/}
                      {/*</div>*/}

                      {/*<div className={'chat-message'}>*/}
                        {/*<div className={'chat-message-content-w'}>*/}
                          {/*<div className={'messegesChat'}>Slept train nearby a its is design size agreeable. And check*/}
                            {/*cons, but countries the was to such any founding company*/}
                          {/*</div>*/}
                        {/*</div>*/}
                        {/*<div className={'chat-message-avatar'}>*/}
                          {/*<img src="/assets/images/avatar3.jpg" alt=""/>*/}
                        {/*</div>*/}
                        {/*<div className="chat-message-date">9:12am</div>*/}
                      {/*</div>*/}


                    </div>



                    <Toolbar className="toolbarCard header-page-chat-bottom-sticky"
                             style={{
                               borderTop: '1px solid #ddd',
                               borderLeft: '1px solid #ddd',
                               borderRadius: 0,
                               backgroundColor: '#f5f1ee',
                               marginRight:-1
                             }}>
                      <ToolbarGroup className={'fullWidthButton'}>
                        <Input placeholder="Type your message here... " onChange={(e)=>this.chatStore.writeMessage(e.target.value)} value={this.chatStore.lineMessage} onPressEnter={()=>this.sendMessage()}/>
                      </ToolbarGroup>
                    </Toolbar>
                    </div>
                    )
                    :
                    <div className={'containerRightListChatInner'} style={{textAlign:'center'}} >
                      <img src='/assets/images/emptyState/empty-chat.png' style={{width:'50%'}}/>
                      <h2>Select user to start chatting</h2>
                      <h3 style={{color:'#bababa'}}>Connect with store or customer to make transaction more fun and easy</h3>
                    </div>
                  }


                </div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    );
  }
}
