import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import CustomButton from '../components/customButton';
import { globalStyles,customStyles,GetPageTheme,customeButtons } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,KeyboardAvoidingView,Animated, ImageBackground, FlatList} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,copyrightText,baseurl} from '../constants/constants';
import {_checkLocationPermission} from '../components/geolocation';
import OtpInputs from 'react-native-otp-inputs';
import SplashScreen from 'react-native-splash-screen';
import CustomLoader from '../components/CustomLoader';
import DeviceInfo from 'react-native-device-info';
import {getDownloadJson, UploadData2,UploadData} from '../controller/functions';
import moment from 'moment';
import { SvgUri, SvgXml} from 'react-native-svg';
import GradientButton from '../components/gradientButton';
import { Ionicons ,Fontisto, AntDesign} from '../components/icons';
import LinearGradient from 'react-native-linear-gradient';

import Graphic1 from '../assets/performics/oqad_graphic.svg';
import { getMethodName, METHODS } from '../constants/methodNames';

function One_QAD(props) { 
  const route = useRoute();
  const ST=props.StaticText || {};
  // get all theme styles acc to current theme set 
  const PageTheme=GetPageTheme(props.DarkMode,route.name);
  const customStyle=customStyles(props.DarkMode,route.name);
  const customeButton=customeButtons(props.DarkMode,route.name);
  const todayDate=moment(new Date()).format('DD/MM/YYYY');

  const AnswerTimeOut=props.OQAD_TimeOut;
  var globalTimer=AnswerTimeOut;
  const timerRef = useRef({});
  const timerAnimated = useRef(new Animated.Value(0)).current;
  const [answers, setAnswers] = useState({});
  const [rerenderdata, setrerenderdata]= useState(0);
  const [processing, setProcessing] = useState(false);
  const [currentQtn, setCurrentQtn] = useState(1);
  const [totalQtn, setTotalQtn] = useState(0);
  const [answerTimer, setAnswerTimer] = useState({"1":globalTimer});
  const [qad, setQad] = useState([]);

  
    useEffect(() => {    
        SplashScreen.hide();        
        get_OQAD();
    }, []);

    useEffect(() => {  
        console.log('currentQtn chnge'); 
        let cqtn=currentQtn;
        if(currentQtn>1){
        let item=qad.length>0? qad[(cqtn-1)]:null;
        if(item){
            let qid=item.QuestionId;
            let qtnKey=qid+'_question';
            let show_qtnKey=qid+'_question_show';
            let AllAns=answers;
            console.log(answerTimer);
            
            if(AllAns[qtnKey]==null && AllAns[show_qtnKey]==null){
                globalTimer=AnswerTimeOut;
                let atimerarr=answerTimer;
                atimerarr[cqtn]=AnswerTimeOut;
                setAnswerTimer(atimerarr); 
                timerAnimated.setValue(0);
                setTimer(); //restart timer
            }
        }
        }
    }, [currentQtn]);


    async function get_OQAD(){
        setProcessing(true);
        let token = await get_item('loginToken');
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        var data = {Downloadtype: 'OQAD',username: loginDetails.UserId,empid: '',token: token,};

        const url=(props.baseurl || baseurl)+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        console.log(url,data);
        await getDownloadJson(url, data)
        .then(async(res) => { 
            setProcessing(false);     
            console.log('res:',res);  
            if (res.OQAD!=null) {
                let QAD_arr=res.OQAD|| [];
                let allQADS=[];
                
                var qad_data={};
                var qids=[];
                for(var i=0;i<QAD_arr.length;i++){
                    let data=QAD_arr[i];
                    let isadded=false;                    
                    
                    if(qids.indexOf(data.QuestionId)<0){
                        if(Object.keys(qad_data).length>0) allQADS.push(qad_data);
                        qids.push(data.QuestionId)
                        qad_data={};
                        qad_data['QuestionId']=data.QuestionId;
                        qad_data['Question']=data.Question;
                        qad_data['Options']=[{'AnswerId':data.AnswerId,'Answer':data.Answer}];
                        if(data.RightAnswer==true) qad_data['Answer']=data.AnswerId;   
                                           
                    }
                    else{
                        let ops=qad_data['Options'] || [];
                        ops.push({'AnswerId':data.AnswerId,'Answer':data.Answer});
                        if(data.RightAnswer==true) qad_data['Answer']=data.AnswerId;  
                         
                    } 
                }
                
                allQADS.push(qad_data);
                setQad(allQADS);
                setTotalQtn(allQADS.length);
                setTimer(false,false,allQADS);
                
            }
            else if(typeof(res)=='object' && res.length>0 && res[0].Result!=null && res[0].Result.includes('No Data')){
                // OQAD Not Found
                goToHome();
            }
        })
        .catch(err => {
            console.log('onPage Team error', err);
        });
        
    }

  
    async function submitAnswer(){
        if(validate()){
        setProcessing(true);
        let token = await get_item('loginToken');
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const today=moment(new Date()).format('MM/DD/YYYY');

        var user_answers=[];
        for (const qtn_key in answers){
            const item=answers[qtn_key];
            console.log(qtn_key); 
            if(qtn_key.includes('_question_show')){
                console.log('showed question');
                let qid=qtn_key.replace('_question_show','');
                let answerid=0;
                var ans_obj={"ANSWER_ID":answerid,"QUESTION_ID":qid,"VISIT_DATE":today,"USER_NAME":loginDetails.UserId};
            }
            else if(qtn_key.includes('_question')){
                console.log('qtn replied')
                let qid=item.qid;
                let answerid=item.selId;
                var ans_obj={"ANSWER_ID":answerid,"QUESTION_ID":qid,"VISIT_DATE":today,"USER_NAME":loginDetails.UserId};
            }
            user_answers.push(ans_obj);
        }
        let post_data={
            "MID":"0",
            "Keys": "TODAY_ANSWER",
            "JsonData":JSON.stringify(user_answers),
            "UserId": loginDetails.UserId
        }

        

        const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
        
        console.log('OQAD upload ',url,post_data);
        
        await UploadData2(url, post_data)
        .then(async(res) => {             
            setProcessing(false); 
            console.log(res);      
            if(res.UploadJsonResult=='Success'){
                
            }
            goToHome();
            
        })
        .catch(err => {
            console.log('onPage Team error', err);
        });
        }
    }

    async function goToHome(){
        let params=props.route.params? props.route.params:{};
        let isTodayLogin=params.TodayLogin!=null?params.TodayLogin:false;
        // props.setLoginExists(false);
        props.navigation.reset({index: 0,routes: [{name: 'NoticeBoard',params:{'TodayLogin':isTodayLogin}}],});
    }

    async function goToNext(){
        if(validate()){
            let cqtn=currentQtn;
            cqtn=cqtn<qad.length?cqtn+1:cqtn;                                 
            setCurrentQtn(cqtn);
        }
    }

    async function goToPrev(){
        let cqtn=currentQtn;
        cqtn=cqtn>1?cqtn-1:cqtn;
        setCurrentQtn(cqtn);
    }

    function setTimer(reset,stop,allQADS=[]){ 
        let arr=timerRef.current; 
        if(stop){
            console.log('clearTimeout',arr[currentQtn],currentQtn,arr);
            if(arr[currentQtn]){clearTimeout(arr[currentQtn]);}
        }
        else{
            reset?globalTimer=AnswerTimeOut:--globalTimer;
            if(globalTimer>=0){
                let atimerarr=answerTimer;
                atimerarr[currentQtn]=globalTimer;

                if(timerAnimated){
                    Animated.timing(timerAnimated, {
                        toValue: (AnswerTimeOut-globalTimer),
                        duration:1100,
                        useNativeDriver:false,
                    }).start();
                }
                
                // console.log('atimerarr',currentQtn,globalTimer,atimerarr);
                setAnswerTimer(atimerarr);
                setrerenderdata(globalTimer);
                arr[currentQtn]=setTimeout(()=>{ setTimer(false,false,allQADS);},1000);
            }
            else{showAnswer(allQADS);}  
        }
         
    }

    async function selectAnswer(item,option){
        console.log('selectAnswer');
        let qid=item.QuestionId;
        let qtnKey=qid+'_question';
        let AllAns=answers;
        if(AllAns[qtnKey]==null){
            AllAns[qtnKey]={'selId':option.AnswerId,'selText':option.Answer,'qid':qid};
        }
        setTimer(false,true); // stop timer
        setAnswers(AllAns);
        console.log('selectAnswer:',AllAns);
        setrerenderdata(!rerenderdata);
        
    }

    async function showAnswer(allQADS=[]){
        let item=allQADS.length>0 && currentQtn>=1?allQADS[(currentQtn-1)]:null;
        
        if(item!=null){
            let qid=item?item.QuestionId:'';
            let show_qtnKey=qid+'_question_show';
            let AllAns=answers;
            if(AllAns[show_qtnKey]==null){
                AllAns[show_qtnKey]=true;
            }
            setAnswers(AllAns);
            console.log('showAnswer:',AllAns);
            setrerenderdata(!rerenderdata);
        }       
    }
    

    const validate=()=>{  
        let item=qad.length>0? qad[(currentQtn-1)]:null;
        if(item){
            let qid=item.QuestionId;
            let qtnKey=qid+'_question';
            let show_qtnKey=qid+'_question_show';
            let AllAns=answers;
            if(AllAns[qtnKey]==null && AllAns[show_qtnKey]==null){
                notify(ST.Pleaseselectyouranswer,'SHORT');
                return false;
            }
        }
        return true;
    }

    const validate2=()=>{  
        
        if(qad.length>0){
            for(var i=0;i<qad.length;i++){
                let item=qad[i];
                let qid=item.QuestionId;
                let qtnKey=qid+'_question';
                let AllAns=answers;
                if(AllAns[qtnKey]==null){
                    notify(ST.Pleaseselectyouranswer,'SHORT');
                    return false;
                }
            }            
        }
        return true;
    }

  return ( 
    <Container {...props}>
        <StatusBar barStyle={"light-content"} backgroundColor={PageTheme.$primary_color} />
        {processing && <CustomLoader />} 
        <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.qad_bg}>
            <View style={customStyle.qad_hdr}>
                <Text style={[customStyle.qad_subtext]}>{ST.HeyThere}</Text>
                <Text style={customStyle.qad_text}>{ST.OneQuestionADay}</Text>
                <SvgXml width={190} height={160} xml={Graphic1}/>    
            </View>
            
            <View style={customStyle.qadPopUp}>
                {/* <ScrollView
                    style={[customStyle.qadScrollCon]}
                    contentContainerStyle={customStyle.qadInnerCon}
                    
                >    */}
                <View style={customStyle.qadPopUpInner}>                
                    <View style={customStyle.linear_progressBarWrapper}>
                        <View style={customStyle.linear_progressBar}>
                        <View style={[customStyle.linear_progressBar_bg]}></View>
                        <View style={[customStyle.linear_progressBar_filled,{width:(totalQtn>0?(((currentQtn/totalQtn)*100)+'%'):'100%')}]}></View>
                        </View>
                        <Text style={customStyle.linear_progressBarText}>{currentQtn+'/'+totalQtn}</Text>
                    </View>
                    <View style={customStyle.qad_form}>
                        { qad.length>0 &&
                        <FlatList
                        data={qad}
                        extraData={rerenderdata}
                        style={[customStyle.qadScrollCon]}
                        contentContainerStyle={customStyle.qadInnerCon}
                        removeClippedSubviews={false}
                        renderItem={({item,index})=>{
                            let Options=item.Options;
                            let qid=item.QuestionId;
                            let qtnKey=qid+'_question';
                            let show_qtnKey=qid+'_question_show';
                            let AllAns=answers;

                            let showAnswer=AllAns[show_qtnKey]!=null?AllAns[show_qtnKey]:false;                            
                            let selAns=AllAns[qtnKey]!=null?AllAns[qtnKey]['selId']:'';
                            console.log('AllAns',showAnswer);

                            let prev_time=answerTimer[currentQtn]<AnswerTimeOut?answerTimer[currentQtn]+1:answerTimer[currentQtn];
                            let curr_time=answerTimer[currentQtn];
                            var width='100%';
                            // console.log('timerAnimated:',timerAnimated,prev_time,curr_time);
                            if(timerAnimated!=null && prev_time!=null && curr_time!=null){
                            width=timerAnimated.interpolate({
                                inputRange:[(AnswerTimeOut-prev_time),(AnswerTimeOut-curr_time)],
                                outputRange:[((prev_time/AnswerTimeOut)*100)+'%',((curr_time/AnswerTimeOut)*100)+'%'],
                            });
                            }

                            
                            return(
                                <View key={index} style={[customStyle.qad_questions,(index==(currentQtn-1)?customStyle.qad_questionsShow:{})]}>
                                    <Text  style={customStyle.qad_qtnText}>{item.Question}</Text>
                                    <View style={customStyle.qad_optionsCon}>
                                    { Options.length>0 &&
                                        Options.map((option,op_index)=>{
                                            let show_diff_bg=(item.Answer && ((selAns!='' && selAns!=null) || showAnswer) 
                                            && (item.Answer==option.AnswerId || ((selAns!='' && selAns!=null) && selAns==option.AnswerId)))  ?true:false;
                                            
                                            let ansbgColor=((selAns!='' && selAns!=null) && selAns==option.AnswerId && (item.Answer!=selAns))?'red':'green';
                            
                                            let opbg=show_diff_bg?{backgroundColor:ansbgColor}:{};
                                            let opcolorText=show_diff_bg?{color:'#fff'}:{};
                                            let isD=((selAns!='' && selAns!=null) || showAnswer);
                                            let isdisabled=(((selAns!='' && selAns!=null) || showAnswer) && item.Answer!=null && item.Answer!=option.AnswerId);
                                            let disablebg=(isdisabled?{backgroundColor:PageTheme.$text_color_500}:{});
                                            let disabletext=(isdisabled?{color:PageTheme.$accent_color}:{});
                                            
                                            return(
                                                <TouchableOpacity key={op_index} style={[customStyle.qad_optionBtn,disablebg,opbg]} disabled={isD} onPress={()=>{selectAnswer(item,option)}}>
                                                    <Text style={[customStyle.qad_optionBtnText,disabletext,opcolorText]}>{option.Answer}</Text>
                                                </TouchableOpacity>
                                            )
                                        })
                                    }
                                    </View>
                                    <View style={customStyle.qad_timer_wrapper}>
                                        <AntDesign name='clockcircleo' color={PageTheme.$secondary_color_dark} size={30}/>
                                        <Text style={customStyle.qad_timerText}>{answerTimer[currentQtn]+'s'}</Text>
                                        <View style={customStyle.timerProgressBar}>
                                            <View style={customStyle.timerProgressBar_bg}></View>
                                            {/* <View style={[customStyle.timerProgressBar_filled,{width:((answerTimer[currentQtn]/10)*100)+'%'},{backgroundColor:(answerTimer[currentQtn]<3?'red':(answerTimer[currentQtn]<7?'#ff8100':'green'))}]}></View> */}
                                            <Animated.View style={[customStyle.timerProgressBar_filled,{width:width},{backgroundColor:(answerTimer[currentQtn]<(parseInt(AnswerTimeOut/4))?'red':(answerTimer[currentQtn]<(parseInt(AnswerTimeOut/2))?'#ff8100':'green'))}]}></Animated.View>
                                        
                                        </View>
                                    </View>
                                    {(selAns==item.Answer && (selAns!=null && selAns!=''))  &&
                                    <View style={customStyle.answerRemark}><Text  style={customStyle.answerRemarkText}>{ST.WellDoneGoodJob}</Text></View>
                                    }
                                    {(selAns!=item.Answer && ((selAns!=null && selAns!='') || showAnswer)) &&
                                    <View style={[customStyle.answerRemark,customStyle.remarkRedbg]}><Text  style={[customStyle.answerRemarkText,customStyle.remarkRed]}>{ST.OopsBetterlucknexttime}</Text></View>
                                    }
                                    { index==( qad.length-1) && 
                                        <View style={customStyle.qad_qtnBtnsGrp}>
                                            { (index!=0) && 
                                            <TouchableOpacity activeOpacity={0.6} onPress={()=>{goToPrev();}} style={[customStyle.qad_qtnBtn,customStyle.qad_btnBack]}>
                                                <Text style={[customStyle.qad_qtnBtnText,customStyle.qad_btnBackText]}>{ST.Back}</Text>
                                            </TouchableOpacity>
                                            }
                                            <TouchableOpacity activeOpacity={0.6} onPress={()=>{submitAnswer();}} style={[customStyle.qad_btnSubmitCon]}>
                                                <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$gradient2, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.qad_btnSubmit]}>
                                                    <Text style={[customStyle.qad_qtnBtnText,customStyle.qad_btnNextText]}>{ST.Submit}</Text>
                                                </LinearGradient>
                                            </TouchableOpacity>
                                        </View>
                                    }
                                    { index<( qad.length-1) && 
                                        <View style={customStyle.qad_qtnBtnsGrp}>
                                            {(index!=0) && 
                                            <TouchableOpacity activeOpacity={0.6} onPress={()=>{goToPrev();}} style={[customStyle.qad_qtnBtn,customStyle.qad_btnBack]}>
                                                <Text style={[customStyle.qad_qtnBtnText,customStyle.qad_btnBackText]}>{ST.Back}</Text>
                                            </TouchableOpacity>
                                            }
                                            <TouchableOpacity activeOpacity={0.6} onPress={()=>{goToNext();}} style={[customStyle.qad_qtnBtn,customStyle.qad_btnNext]}>
                                                <Text style={[customStyle.qad_qtnBtnText,customStyle.qad_btnNextText]}>{ST.Next}</Text>
                                            </TouchableOpacity>
                                        </View>
                                    }
                                </View>
                            )
                        }}
                        
                        />                                           
                        }
                    </View>
                    
                </View>
                {/* </ScrollView>  */}
                <View style={[customStyle.signatureBox,customStyle.mt50]}>
                    <Text style={customStyle.signatureText}>{version}</Text>
                    <Text style={customStyle.signatureText}>{copyrightText}</Text>
                </View>
            </View>
        </LinearGradient>        
    </Container>   
  ); 
}

export default connect(mapStateToProps, mapDispatchToProps)(One_QAD)