import React, { useContext, useEffect, useRef, useState } from "react";
import './mainPart.css';
import { MainPartHeader } from "./mainPartHeader";
import { ContentContainer } from "./contentContainer";
import { MainPartFooter } from "./main-part-footer";
import { OrLineContainer } from "./orLineContainer";
import { CSSTransition, SwitchTransition, TransitionGroup } from "react-transition-group";
import { CalendarComponent } from "./calendar/calendar";
import { PlanContentContainer } from "./planContentContainer";
import { TimeSelector } from "./timeSelector/timeSelector";
import { Form } from "./form/form";
import { LangDict } from "../langDict";
import { ContextLang } from "../ContextLang";
import { ContextWs } from "../../ContextWs";

type TProps = {
    createSess: () => void,
    connectSess: () => void
}

type FormData = {
    phone: string
    email: string
    firstName: string
}

export const MainPart: React.FC<TProps> = React.memo((props) => {    
    const {lang, setLang} = useContext(ContextLang);
    const changeContent = useRef(0);
    const [showBackground, setShowBackground] = useState<boolean>(false);
    const [planContent, setPlanContent] = useState<JSX.Element>();
    const defaultCurrentContent = 
        <ContentContainer 
            titleText={LangDict.mainTitle}
            descriptText={LangDict.mainDescription}
            onClickButton={() => onClickStartDemo()}
            textButton={LangDict.startDemoButton}
        />
    const [currentContent, setCurrentContent] = useState<JSX.Element>(defaultCurrentContent);  
    const lastRender = currentContent;
    const history = useRef<Array<JSX.Element>>(new Array());
    const isRemoveLastElementHistry = useRef<boolean>(false);

    useEffect(() => {
        console.log(lang)
        // onClickStartDemo()
        setCurrentContent(lastRender)
        
    }, [lang]);

    useEffect(() => {
        if(planContent && !isRemoveLastElementHistry.current) {
            history.current.push(planContent);
            isRemoveLastElementHistry.current = false;
            console.log(history.current.length, 'добавили 1')
        }
    }, [planContent])
    
    function changeLang(lang: 'ru' | 'en') {
        setLang(lang);
        document.querySelector('html').lang = lang;
    }

    function changeContentFunc() {
        changeContent.current += 1
    }

    function prevPlan() {
        changeContentFunc();
        if(history.current.length - 1 <= 0) {
            onClickStartDemo();
            history.current = new Array();
            setPlanContent(null);
            disableBackground();
            isRemoveLastElementHistry.current = false;
        } else {
            setPlanContent(history.current[history.current.length - 2]);
            history.current.splice(history.current.length - 1, 1);
            isRemoveLastElementHistry.current = true;
            console.log(history.current.length, 'убрали 1')
        }
        
    }

    function onClickStartDemo() {
        changeContentFunc();
        setCurrentContent(
            <>
                <ContentContainer 
                    titleText={LangDict.startDemoTitle}
                    descriptText={LangDict.startDemoDescriptionStart}
                    onClickButton={() => onClickCreateNewDemo()}
                    textButton={LangDict.startNewDemoButton}
                    />
                <OrLineContainer text={LangDict.orLine}/>
                <ContentContainer 
                    descriptText={LangDict.startDemoDescriptionEnroll}
                    onClickButton={() => onClickPlaneDemo()}
                    textButton={LangDict.enrollNewDemoButton}
                />
            </>
        )        
    } 

    function onClickCreateNewDemo() {
        props.createSess();
        changeContentFunc();
        setCurrentContent(
            <ContentContainer 
                titleText={LangDict.demoStartedTitle}
                descriptText={LangDict.demoStartedDescription}
                onClickButton={() => onClickConnect()}
                textButton={LangDict.connectToDemoButton}
                isAccessCode={true}
            />
        )            
    }

    function onClickPlaneDemo() { 
        // changeContentFunc()
        isRemoveLastElementHistry.current = false;
        enableBackground();
        setPlanContent(
            <PlanContentContainer 
                title={LangDict.selectDate}
                content={<CalendarComponent onCLick={(date) => onSelectDay(date)} />}
                isLegend={true}
                toPrevState={prevPlan}
                showPrevButton={true}
            />
        );
        setCurrentContent(<></>);
    }

    function onClickConnect() {
        props.connectSess()
        // ws.send('{ "message" : "NEW_SESS" }');
    }

    function onSelectDay(date: {ru: string, en: string}) {
        // history.current.push(planContent);
        isRemoveLastElementHistry.current = false;
        changeContentFunc()
        setPlanContent(
            <PlanContentContainer 
            title={LangDict.selectTime}
                date={date}
                content={<TimeSelector 
                    date={date}
                    onClickTime={(date, time) => onSelectTime(date, time)}                
                />}
                isLegend={true}
                toPrevState={prevPlan}
                showPrevButton={true}
            />
        );
    }

    function onSelectTime(date: {ru: string, en: string}, time: string) {
        // history.current.push(planContent);
        isRemoveLastElementHistry.current = false;
        changeContentFunc()
        let dateTime = `${date} ${lang === 'ru' ? 'в' : 'in'} ${time}`;
        let dateObj = {
            ru: `${date.ru} в ${time}`,
            en: `${date.en} in ${time}`
        }
        setPlanContent(
            <PlanContentContainer
                title={LangDict.checkout}
                date={dateObj}
                content={
                    <Form 
                        onSubmit={(data, date) => onSubmit(data, date)} 
                        dateInfo={dateTime}
                    />
                }
                isLegend={false}
                toPrevState={prevPlan}
                showPrevButton={true}
            />
        )
        console.log(dateTime)
    }

    function onSubmit(data: FormData, date: string) {        
        changeContentFunc();
        setPlanContent(null);
        setCurrentContent(
            <ContentContainer 
                titleText={LangDict.checkouted}
                descriptText={LangDict.checkoutedDescription}
                textButton={LangDict.toHomeButton}
                onClickButton={() => toMain()}
            />
        )
        history.current = new Array();
        // console.log(data, date)
    }

    function toMain() {
        changeContentFunc();
        setCurrentContent(defaultCurrentContent);
        setPlanContent(null);
        disableBackground();
        history.current = new Array();
    }

    function enableBackground() {
        setShowBackground(true);
    }

    function disableBackground() {
        setShowBackground(false);
    }

    return <div className="main-part-container">
        <div className="background-image"></div>
        <MainPartHeader changeLang={(lang) => changeLang(lang)} onClickLogo={toMain}/>
        <SwitchTransition mode="out-in">
            <CSSTransition
                key={changeContent.current}
                //@ts-ignore
                addEndListener={(node, done) => node.addEventListener("transitionend", done, false)}
                classNames={'change-main-part-content'}
            >
                <div className="main-part-content">            
                    {currentContent}                
                </div>
            </CSSTransition>            
        </SwitchTransition>        
        {
            planContent ?
            <SwitchTransition mode="out-in">
                <CSSTransition
                    key={changeContent.current}
                    //@ts-ignore
                    addEndListener={(node, done) => node.addEventListener("transitionend", done, false)}
                    classNames={'change-main-part-content'}
                >
                <div className="main-part-plan-content">
                    {planContent}
                </div>
            </CSSTransition>
            </SwitchTransition>
            : null
        }        
        <CSSTransition
            in={showBackground}
            timeout={300}
            classNames='show-background'
            unmountOnExit            
        >
            <div className="background-container"></div>
        </CSSTransition>
        <MainPartFooter />
    </div>
})