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} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {db, colors_Arr, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, FontAwesome} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { Q_getContractFormPrograms} from '../constants/ConstantQueries';

function ContractPrograms(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();
    const [storeData, setStoreData] = useState({});
    const [dailyMenu, setDailyMenu] = useState([]);
    const [refreshMenuRender, setRefreshMenuRender] = useState(0);
    const [isLoaded, setIsLoaded] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    
  
    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        
        setStoreData(storeData1);
       
        getData(storeData1);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            getData(storeData1);
        });

        return willFocusSubscription;
    }, []);

  
    async function getData(storeData1){
      setProcessing(true);
     
        try {   
          let d1=new Date();
          let d2=moment(d1).format('MM/DD/YYYY');
          let {StoreId}=storeData1;
          
          let q=await Q_getContractFormPrograms(storeData1);
         
          await db.transaction(async function (txn) {     
            await txn.executeSql(q,[],async function (txn2, txnres) { 
              console.log('contract programs count:',txnres.rows.length);
              if(txnres.rows.length>0){     
                let arr=[]; 
                for(var i=0;i<txnres.rows.length;i++){
                  let data =txnres.rows.item(i);
                  let {ContractFormStatus}=data;
                  
                  let isDone=ContractFormStatus!=null && ( ContractFormStatus==1 || ContractFormStatus=='1')?true:false;
                  
                  data['isDone']=isDone;
                  arr.push(data);
                  if(i==(txnres.rows.length-1)){
                    setDailyMenu(arr);
                    setProcessing(false);
                  }
                }
              }
              else{
                setProcessing(false);
              }
            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);

          });          
        } catch (err) {
          console.log(err);          
        }        
    }
 
    async function goto_ContractForm(item){
        if(item.ContractFormStatus=='1' || item.ContractFormStatus==1){
            notify(`Contract form for ${item.ProgramName} is already Filled`)
        }
        else{
            props.navigation.navigate("ContractForm",{storeData:storeData,program:item})
        }
    }

 
  

    // function _renderLeftMenuItem(index,RowContent){
    //   return(
    //     <View style={customStyle.dialyMenu_Rows} key={index}> 
    //       {RowContent[0]}
    //     </View>
    //   )
    // }


    // function _renderRightMenuItem(item,index,RowContent){
    //   return(
    //     <View style={customStyle.dialyMenu_Rows} key={index}> 
    //       {RowContent[0]}
    //       {_renderMenuItem(item,index)}
    //     </View>
    //   )

    // }

    function _renderMenuItem(item,index){
    //   let newi=index>2?((index%3)):index;
    //   let firstitem=(index%2==0)?true:false;            
    //   let arr=colors_Arr[newi]?colors_Arr[newi].bg:colors_Arr["0"].bg;
    //   let unavlbl_bg=['#bfbfbf','#bfbfbf'];
    //   let arr_new=item.isAvlbl==false?unavlbl_bg:arr;
    //   let iconColor=colors_Arr[newi]?colors_Arr[newi].color:colors_Arr["0"].color;
    //   const imgPath='';//item.MenuPath+(item.isAvlbl==false?item.GreyIcon:item.NormalIcon);
      
    //   let m_bgimage=colors_Arr[newi]?colors_Arr[newi].bgImage:colors_Arr["0"].bgImage;
    //   m_bgimage=item.isAvlbl==false?grey_bg_image:m_bgimage;


    //   return(
    //     <TouchableOpacity activeOpacity={(item.isAvlbl==false?1:0.7)}  style={[customStyle.daily_menu_outer,firstitem?customStyle.daily_menu_first:{}]} key={index} onPress={() => {goto_ContractForm(item)}}> 
    //       <View style={customStyle.daily_menu_tilebgShadow}>
    //       <LinearGradient colors={arr_new} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.daily_menu}>
    //       </LinearGradient>  
    //       <View style={[customStyle.daily_menu_innerImgCon]}> 
    //           <SvgXml xml={m_bgimage} width={90} height={90} style={customStyle.daily_menu_bgImg}/>
    //       </View>
    //       <View style={[customStyle.daily_menu_inner2]}> 
    //           {(imgPath!=null && imgPath!='') && <Image source={{uri:imgPath}} style={customStyle.daily_menu_Icon}/>}
    //       </View>
          
    //       <Text style={customStyle.daily_menu_title}>{item.ProgramName}</Text>
    //       {item.isKPI_Done==true &&
    //         <View style={customStyle.daily_menu_done}><AntDesign color={'green'} size={30} name='checkcircle'/></View>
    //       }  
    //       </View>     
    //     </TouchableOpacity>
    //   )
        return (
            <View style={customStyle.opening_Stock_wrap} key={index}>
                <View style={customStyle.opening_Stock_cat}>   
                    <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr} onPress={()=>{goto_ContractForm(item)}}>                  
                        <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                            <Text style={customStyle.opening_Stock_catText}>{item.ProgramName}</Text>
                        </LinearGradient>
                        {(item.isDone!=null && item.isDone==true) && <View style={[customStyle.stockCatDone_check]}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                        {((item.isDone==null || item.isDone==false) && item.IsDataExists!=null && item.IsDataExists=='1') && <View style={[customStyle.ContrForm_hasData]}><FontAwesome color={'green'} size={20} name='dot-circle-o'/></View>}
                        
                    </TouchableOpacity>
                </View>
            </View>
        )
    }


    function _renderDailyMenu(){
      var RowContent=[];
      return(
        <>
          {refreshMenuRender==refreshMenuRender && dailyMenu.length>0 &&
            dailyMenu.map((item,index)=>{ 
            //   let firstitem=(index%2==0)?true:false;
              
            //   if(firstitem){
            //     var content=_renderMenuItem(item,index);
            //     RowContent=[content];
            //     if(index==dailyMenu.length-1){
            //       return _renderLeftMenuItem(index,RowContent);
            //     }
            //   }
            //   else{
            //     return _renderRightMenuItem(item,index,RowContent);
            //   }
            return _renderMenuItem(item,index);
              
            })
          }
        </>
        
      );
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}> 
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={'Contract Form Programs'}/> 
       
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&
            <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>            
            
              <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>
                <View style={customStyle.storel_card_outer}> 
                    <View style={customStyle.storel_card}>
                    <View style={customStyle.storel_card_content}>
                        <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                        <View style={customStyle.storel_card_subtitle}>
                        <Text style={customStyle.storel_card_subtitleTxt}>{storeData.StoreType}</Text>
                        </View>
                    </View>                  
                    </View>
                    <View style={customStyle.storel_details}>
                    <View style={customStyle.storel_code}>
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                        </View>                    
                        <View style={[customStyle.storel_codeCon]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                        </View>
                    </View>
                    </View>                
                </View>
              </View>

              {_renderDailyMenu()}  
            </ScrollView>
          }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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