import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, KeyboardAvoidingView, BackHandler, Keyboard} from 'react-native';
import { connect,  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {db, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { getKPIFields, goToMenuPage } from '../controller/functions';
import { getProgramChecklistAvailableQ } from '../constants/ConstantQueries';
import GradientButton from '../components/gradientButton';


function ProgramChecklist(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);
    const [isStoreSearch, SetIsStoreSearch] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [program, setProgram] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [ScreenName, setScreenName] = useState("");
    const [BgNav, setBgNav] = useState(false);
    const [BgNavData, setBgNavData] = useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [CheckList, setCheckList] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);

    const [showAlert, setShowAlert] = useState(false);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [Hdrname, setHdrname] = useState("");
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let program1=params.CatData || {};
        let menu1=(params.menu || params.MenuItem) || {};
        let isAdhoc=params.isAdhoc || false;
        let isBeat=params.isBeat!=null? params.isBeat : false;
        let isNonMerchan1=params.isNonMerchans!=null? params.isNonMerchans : false;
        let isNonProgam=params.isNonProgs!=null? params.isNonProgs : false;
        let isStoreSearch=params.isStoreSearch!=null? params.isStoreSearch : false; 
        let screenname1=params.screenname!=null? params.screenname : "";
        let BgNav1=params.redirect!=null? params.redirect : false;
        let BgNavData1=params.BgNavData!=null? params.BgNavData : {};
      
        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setIsNonMerchan(isNonMerchan1)
        setIsNonProg(isNonProgam)
        SetIsStoreSearch(isStoreSearch)
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        setScreenName(screenname1);
        setBgNav(BgNav1);
        setBgNavData(BgNavData1);
        setProgram(program1);
            
        getData(storeData1,program1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch);

      
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            getData(storeData1,program1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch);
        });

        return function cleanup() {
            
            return willFocusSubscription
        };
       
    }, []);
    

    async function getData(storeData1,program1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch){   
          
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
           
            let AllKPIFields=await getKPIFields(menu1);
            setKPIFields(AllKPIFields);

            await db.transaction(async function (txn) {  

                let q=await getProgramChecklistAvailableQ(storeData1,menu1,program1);
                console.log("checklist q:",q);
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    console.log('program checklist len:',txnres2.rows.length)
                    
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            if(i==0){
                                program1["Grade"]=data["Grading"] || "";
                                let pDate=data["VisitDate"] || "";
                                program1["AuditDate"]=pDate!=null && pDate!=""?moment(pDate,"MM/DD/YYYY").format("DD/MM/YYYY"):"";
                            }
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                setCheckList(arr);
                                setProgram(program1);
                                setProcessing(false);
                                setrerenderdata(!rerenderdata);
                            }                                
                        }
                        
                    }else{
                        // Forward to menu screen if No data for Program Checklist is Available 
                        movetoMenuScreen(storeData1,menu1,program1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch);
                    }
                },function (txnE,txnerr) { 
                    console.log(txnerr);
                    setProcessing(false);
                    notify("Error while loading checklist!");
                },);
            });          
        } catch (err) {
          console.log(err); 
          setProcessing(false);
          notify("Error while loading checklist!");  
        }        
    }

    async function movetoMenuScreen(storeData1,menu1,program1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch){
        // let obj={props,'screenname':"ProgramQuestions",'storeData':storeData1,'MenuItem':menu1,'ShowCatWise':true,'CatData':program1,'BgNav':BgNav1,'BgNavData':BgNavData1,'isAdhocScreen':isAdhoc,'isBeatPlan':isBeat,'isNonMerchan':isNonMerchan1,'isNonProg':isNonProgam}
        props.navigation.replace("ProgramQuestions",{storeData:storeData1,menu:menu1,'isAdhoc':isAdhoc,'isBeat':isBeat,'isNonMerchans':isNonMerchan1,isNonProgs:isNonProgam,isStoreSearch:isStoreSearch,'redirect':BgNav1,'BgNavData':BgNavData1,'ShowCatWise':true,'CatData':program1})
    }



    function _renderChecklist(){
        return (
            <View style={customStyle.progCh_Con}>
                <View style={customStyle.progCh_TblHeader}>
                    <View style={[customStyle.progCh_TblHeaderBox,customStyle.progCh_TblHeaderBox1]}>
                        <View style={[customStyle.progCh_TblHeaderBoxI]}>
                            <Text style={customStyle.progCh_TblHeaderTxt}>Checklist</Text>
                        </View>
                    </View>
                    <View style={[customStyle.progCh_TblHeaderBox,customStyle.progCh_TblHeaderBox2]}>
                        <View style={[customStyle.progCh_TblHeaderBoxI]}>
                            <Text style={customStyle.progCh_TblHeaderTxt}>Status</Text>
                        </View>
                    </View>
                </View>
                {rerenderdata==rerenderdata && 
                CheckList.map((item,index)=>{
                  
                    return(
                        <View style={customStyle.progCh_TblBRow}>
                            <View style={[customStyle.progCh_TblBCol,customStyle.progCh_TblBCol1]}>
                                <View style={customStyle.progCh_TblBColI}>
                                    <Text style={customStyle.progCh_TblBText}>{item.Checklist}</Text>
                                </View>
                            </View>
                            <View style={[customStyle.progCh_TblBCol,customStyle.progCh_TblBCol2]}>
                                <View style={customStyle.progCh_TblBColI}>
                                    <Text style={customStyle.progCh_TblBText}>{item.Answer}</Text>
                                </View>
                            </View>
                        </View>
                    );
                })
                }
            </View>
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,customStyle.pageCWrap2]}>
            <View style={customStyle.progCh_InfoCon}> 
                <View style={customStyle.progCh_InfoCard}>
                    <View style={[customStyle.progCh_InfoRow,customStyle.progCh_InfoBB]}>
                        <Text style={customStyle.progCh_InfoLbl}>{'Program:'}</Text>
                        <Text style={customStyle.progCh_InfoText}>{program.ProgramName}</Text>
                    </View>   
                    <View style={[customStyle.progCh_InfoRow]}>
                        <View style={[customStyle.progCh_InfoCol,customStyle.progCh_InfoCol1]}>
                            <Text style={customStyle.progCh_InfoLbl}>{'Grade:'}</Text>
                            <Text style={customStyle.progCh_InfoText}>{program.Grade}</Text>
                        </View>
                        <View style={[customStyle.progCh_InfoCol,customStyle.progCh_InfoCol2]}>
                            <Text style={customStyle.progCh_InfoLbl}>{'Audit Date:'}</Text>
                            <Text style={[customStyle.progCh_InfoText,customStyle.progCh_InfoTextR]}>{program.AuditDate}</Text>
                        </View>
                    </View>   
                  
                </View>  
            </View> 
         
            <ScrollView style={customStyle.progCh_scrollOuter}>
            {Object.keys(storeData).length>0 &&     
                _renderChecklist()
            }
            </ScrollView>

            <View style={[customStyle.progCh_NextBtnWrap]}>
                <TouchableOpacity style={customStyle.progCh_NextBtn} activeOpacity={0.6} onPress={()=>{movetoMenuScreen(storeData,currentMenu,program,BgNav,BgNavData,isAdhocScreen,isBeatPlan,isNonMerchan,isNonProg,isStoreSearch)}}>      
                    <AntDesign name={"arrowright"} size={24} color={PageTheme.$accent_color} />
                </TouchableOpacity>
            </View> 
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}

export default connect(mapStateToProps, mapDispatchToProps)(ProgramChecklist);