import React, { useEffect, useState, useRef } from 'react'
import { connect  } from "react-redux"
import moment from "moment"
import { cellFormatter } from "./chat-cell.formattter"
import ToastComponent from '../../../utility/toast/toast.component'
import GenericModalComponent from '../../../utility/hoc/modal-views/generic.modal.component'
import {MettaSvr_Common} from '../../../../redux/helpers/action-enums'

import { ChatHubTypes } from "../../../../redux/dashboard/chat-box/chat-box.action.types"
import { sendChatAsync, makeConnectionChatToHubAndJoinGroupAsync, startReceivingChatAsync,
     chatServerConnectionFailure, uploadPhoto, fetchChatHistoryAsync, chatHubReset } from "../../../../redux/dashboard/chat-box/chat-box.action"
import "./chat-box.styles.scss"

const ChatBoxComponent = ({ isEducator , isDoctor, isPatient, userName, historicalMessages, messages, errorMessage,groupConnected, subscriptionCodeOfLoggedInPatient,
    doSendChatMessage, startConnection, doDismissError, doListenForMessages, presentError, 
    doUploadPicture,doFetchChatHistory, doClearChatHub, ...props
}) => {

    const messagesEndRef = useRef(null)

    const [fileInput, setFileInput ] = useState(null)
    const [textMessage, setTextMessage] = useState('')
    const [ fullScreenImageUrl, setFullScreenImageUrl ] =  useState(null)

    const { subscriptionCode = subscriptionCodeOfLoggedInPatient } = props
    useEffect(() => {
        if(!!subscriptionCode){
            startConnection({subscriptionCode, userName})
        }else{
            presentError("Invalid Subscription-Code. Cannot initiate chat.")
        }
        return () => {
            doClearChatHub()
        }
    }, [])
    
    useEffect(() => {
        if(groupConnected){
            doFetchChatHistory(subscriptionCode)
            doListenForMessages()
        }
        
    }, [groupConnected])

    useEffect(() => {
        scrollToBottom()        
    },[messages])
    //message sending to clients, on click of send button.
    const sendMessageClicked = () => {

        doSendChatMessage({subscriptionCode, userName, message:textMessage})
        setTextMessage('')
    }

    const fileSelectHandler = (evt) => {
        //todo: Krish use this mehtod as entry point to file upload
        const fileHandle = evt.target.files[0]
        console.log(fileHandle)
        doUploadPicture(subscriptionCode, fileHandle)
    }

    const dismissToast = e => {
        doDismissError()
    }

    const dismissFullImageView = () => {
        setFullScreenImageUrl(null)
    }

    const scrollToBottom = () => {
        const target = messagesEndRef.current
        target.scroll({ top: target.scrollHeight, behavior: 'smooth' })
        
      }
    const tapOnImage = (url) => {
        setFullScreenImageUrl(url)
    }

    return (  
        <div id="frame">
            <div className="content">
                <div className="contact-profile">
                    <h4><i className="icon-bubbles"></i> Communication Chanel</h4>
                </div>
                <div className="messages"  ref={messagesEndRef}>
                    <div className="timeline">
                        <div className="time-label pt-2">
                            <span className="bg-violet">Older Chats</span>
                        </div>
                        { historicalMessages.map((message, index) => (
                            <React.Fragment key={`chat-${index}}`}>
                               { cellFormatter({...message, imageTap:tapOnImage}) }
                            </React.Fragment>
                            )
                        )}
                        
                        {/* new time label starts */}
                        <div className="time-label pt-2">
                            <span className="bg-green">{ moment().format("DD MMM. YYYY")}</span>
                        </div>
                        {/* messages */}
                        { messages.map((message, index) => (
                            <React.Fragment key={`chat-${index}}`}>
                               { cellFormatter({...message,imageTap:tapOnImage}) }
                            </React.Fragment>
                            )
                        )}
                        

                    </div>
                </div>
                <div className="message-input">
                    <div className="wrap">
                        <div className="wrapinput">
                            <input type="text" value={textMessage} onChange={ evt => setTextMessage(evt.target.value)} placeholder="Write your message..." />
                        </div>
                        <div className="wrapattach">
                            <input style={{ display: 'none'}} type="file" 
                                accept=".jpg,.png,.jpeg"
                                onChange={fileSelectHandler}
                                ref={ ref => setFileInput(ref) }
                                />                                    
                            {
                                isEducator || isDoctor || isPatient ?
                                <>
                                    <i className="icon-paper-clip attachment" aria-hidden="true" onClick={() => fileInput.click()}></i>
                                    <button className="submit" onClick={sendMessageClicked}><i className="fa fa-paper-plane" aria-hidden="true"></i></button>
                                </>: null
                            }
                        </div>
                        <div className="clearfix"></div>
                    </div>
                </div>
            </div>
            { !!errorMessage ? <ToastComponent message={errorMessage} onclose={dismissToast}/> : null }
            <GenericModalComponent
                    show={!!fullScreenImageUrl}
                    onHide={() => dismissFullImageView()}
                    title={"Full view"}
                >
                   {!!fullScreenImageUrl ? <img src={fullScreenImageUrl} className="fit-width" alt="no-image" /> : null }
            </GenericModalComponent>
        </div>        
    )
}
 

const mapStateToProps = ({ user, chatter }) => ({
    userName: user.currentUser.email,
    subscriptionCodeOfLoggedInPatient: user.currentUser.subsCode,
    messages: chatter.result,
    errorMessage: chatter.errorMessages,
    groupConnected: chatter.isConnected,
    historicalMessages: chatter.oldResult,
    isDoctor: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Doctor,
    isPatient: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Patients,    
    isEducator: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Educator,    
})

const mapDispatchToProps = dispatch => ({
    doUploadPicture: (scode, fileH) => dispatch(uploadPhoto(scode, fileH)),
    presentError: (body) => dispatch(chatServerConnectionFailure({message: body})),
    doSendChatMessage: (body) => dispatch(sendChatAsync(body)),
    startConnection: (body) => dispatch(makeConnectionChatToHubAndJoinGroupAsync(body)),
    doListenForMessages: () => dispatch(startReceivingChatAsync()),
    doDismissError: () => dispatch({
        type: ChatHubTypes.CHAT_HUB_CLEAR_ERROR_STATE
    }),
    doFetchChatHistory: (scode) => dispatch(fetchChatHistoryAsync(scode)),
    doClearChatHub: () => dispatch(chatHubReset())
})

export default connect(mapStateToProps, mapDispatchToProps)(ChatBoxComponent)