import React, {useState, useEffect} from 'react'
import { connect } from 'react-redux'
import { Redirect, useLocation } from 'react-router-dom'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"

import styled from 'styled-components'
import WithForm from '../utility/hoc/wrapper-form/with-form.component'
import WrapperPanelComponent  from "../utility/hoc/wrapper-panel/wrapper-panel.component"
import WithSpinner from "../utility/hoc/spinner/with-spinner.component"
import { availableCards as cards } from './card-list'
import ToastComponent from "../utility/toast/toast.component"


import './case-history.styles.scss'

const LineProgress = styled.div`
    width: ${({width}) => width}%
`
const CaseHistory = ({submissionErrorMessage, theUser, 
    showNextCardIfAvailable, isSubmitting, onSubmitReport,
    readOnly=false, reportIsLoading, isEducator,
    showCaseHistory, initialValues, submitCaseForm, doDismissError}) => {
    
        
        var totalPages = 5
        const [currentPage, setCurrentPage] = useState( readOnly ? 1 : -1)
        
        const { state } = useLocation()
    
        
    useEffect (() => {        
        //need to change page number
        // console.log(cards)
        if(isNaN(showNextCardIfAvailable) || showNextCardIfAvailable){
            cards.every((card, index) => {
                // Do your thing, then:
                if ( theUser[card.showParameter]) {
                    setCurrentPage(index + 1)
                    return false
                }
                else {                  
                    return true
                }
              })
        }
    },[showNextCardIfAvailable, theUser])

    
    if(!showCaseHistory && !readOnly){
        return  <Redirect to={state?.from || '/dashboard/graphs'} />
    }
    
    const dismissToast = e => {
        doDismissError()
      }

    const doPrevious = () => {
        if (currentPage > 1){    
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
            setCurrentPage(currentPage - 1)
        }
    }

    const doNext = () => {
        if (currentPage < totalPages){  
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;  
            setCurrentPage(currentPage + 1)
        }
    }

    
    const showNextCard = () => {
        const currentCard = cards[currentPage - 1]
        
        if(readOnly && !initialValues){
            return null
        }

        if (!!currentCard){
            const CardWithForm = WithForm(currentCard.element)
            return <CardWithForm initialValues={readOnly ? initialValues : currentCard.initialValue}
                        validationRules={currentCard.validationSchema}
                        identifier={currentCard.id}
                        readOnly={readOnly} isFetching={isSubmitting}
                        rootKey={currentCard.rootKeyInInitialValues}
                        submitTheForm={submitCaseForm} transformData={currentCard.transformData} theUser={theUser}
                        previous={doPrevious} next={doNext} currentPage={currentPage} totalPages={totalPages}                        
                    />
        }
        else
            return null
    }

    const ButtonWithSpinner = WithSpinner(
        () =>
          (
            <div className="d-flex justify-content-end">            
                <div className="shadow-sm p-1 bg-white rounded">
                    <button type="button" className="btn-login" onClick={onSubmitReport}>
                    <FontAwesomeIcon size="2x" icon={`file-pdf`}/></button>
                </div>                 
            </div>                 
        )
    )

    return (
        <div className="page-header-fixed compact-menu page-horizontal-bar">
             <main className="page-content content-wrap">
                <div className="page-inner">
                    {
                        readOnly ? 
                            null :  
                            <div className="page-title clearfix sticky-top">
                                <h3 className="float-left">Case History</h3>
                                <a href="#" className="float-right">
                                    <i className="fa fa-angle-double-left"></i> Go to back</a>
                            
                            </div>
                    }
                   
                    {/** cards start */}
                    <div id="main-wrapper" className="container">
                        <div className="row">
                            <WrapperPanelComponent>
                                <div className="card">
                                        {
                                            currentPage < 0 ? null :
                                            (
                                                <>
                                                    <ul id="progressbar">
                                                        {
                                                            cards.map( (card, index) => {
                                                                
                                                                return <li key={card.id} className={`${index <= currentPage - 1 ? 'active': ''}`} id={card.id}>{
                                                                    card.title
                                                                }</li>
                                                            })
                                                        }
                                                    </ul>
                                                    <div className="progress">
                                                        <LineProgress className="progress-bar progress-bar-animated bgd-green" 
                                                        width={currentPage / totalPages * 100} />                                                        
                                                    </div>                                                    
                                                    {
                                                        showNextCard()
                                                    }
                                                    { !!submissionErrorMessage ? <ToastComponent message={submissionErrorMessage} onclose={dismissToast}/> : null }

                                                </>
                                            )
                                        }
                                            
                                        </div>
                                        {
                                            readOnly && !isEducator? 
                                            <>
                                                <hr/>
                                                <ButtonWithSpinner defaultHeight={false} isLoading={reportIsLoading}/>
                                            </>                                            
                                            :null
                                        }
                                        
                            </WrapperPanelComponent>
                                   
                        </div>
                    </div>
                </div>
             </main>
        </div>
    )
}


export default CaseHistory