import React, { useState, useEffect, memo } from 'react';
import { useIsFocused, useRoute } from '@react-navigation/native';
import { View, Text, TouchableOpacity, Image, FlatList, Platform } from 'react-native';
import { connect } from 'react-redux';
import moment from 'moment';
import Container from '../components/container';
import CustomLoader from '../components/CustomLoader';
import CustomHeader from '../components/customHeader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { get_item } from '../components/localStorage';
import { notify } from '../components/notify';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { getDownloadJson1 } from '../controller/functions';
import { METHODS, getMethodName } from '../constants/methodNames';
import { SvgXml } from 'react-native-svg';
import { AppTables } from '../constants/tableConstants';
import { mapDispatchToProps, mapStateToProps } from '../reducers/contextProvider';
import { db } from '../constants/constants';
import { Fontisto, Ionicons } from '../components/icons';
import DateTimePickerModal from 'react-native-modal-datetime-picker'

const ImageAuditStoreList = (props) => {
  const route = useRoute();
  const { DarkMode, baseurl, StaticText: ST = {} } = props;
  const PageTheme = GetPageTheme(DarkMode, route.name);
  const customStyle = customStyles(DarkMode, route.name);

  const [processing, setProcessing] = useState(false);
  const [loaderTitle, setLoaderTitle] = useState();
  const [isDataFound, setIsDataFound] = useState(false);
  const [addStoreInfo, setAddStoreInfo] = useState([]);
  const [addStoreInfodatewise, setAddStoreInfoDateWise] = useState([]);

  const [localimagedata, setHdrData] = useState([]);

  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
  const [selectedDate, setSelectedDate] = useState(null);

  const isFocused = useIsFocused();

  useEffect(() => {
    setLoaderTitle(ST.Loading +'...');
    Get_data();
  }, [isFocused]);

  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisibility(false);
  };

  const handleConfirm = (date) => {
    setSelectedDate(date); // Save the selected date in state
    hideDatePicker();
  };


    async function getDataselectedDate(date){ 
      const date1 = moment(date).format('MM/DD/YYYY');
        setProcessing(true)   
        try {
          
          let allImageAuditStoreListData= await DownloadImageAuditStoreList(date1);
          // console.log('allImageAuditStoreListData-------------------',allImageAuditStoreListData);
          if(allImageAuditStoreListData?.length>0){
              console.log("localimagedata--",localimagedata)
              
            let res=allImageAuditStoreListData?.map((item)=>{
              console.log("res------12------",item)
              let objVal=localimagedata?.find((val)=>val.MID==item.MID && val.STORE_ID==item.StoreId )
              console.log("res------12-----objVal-",objVal)
              if(objVal && (Object?.keys(objVal)?.length>0)){
                console.log("res------12-----objVal3-")
                return {...item,...objVal };
              }else{
                return item ;
              }
            })

            console.log("res------------",res)
              setAddStoreInfo(res||[]);
              setProcessing(false);
          }
          else{
              notify(ST.Nodatafound);
              setProcessing(false);
          }
    
        } catch (err) {
          setProcessing(false);
          console.log(err);          
        }        
      }
    
    async function DownloadImageAuditStoreList(date1){
        let downloadKey="Sup_ImageAuditStoreList";
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        let data={
          Downloadtype:downloadKey,
          Username: loginDetails.UserId,
          Param1: date1,
          Param2: '',
        };
  
        console.log(url,data);
        return await getDownloadJson1(url,data)
        .then(async(res)=>{  
          if (res[downloadKey]) {
            let data_arr = res[downloadKey] || []; 
            return data_arr;
          }
          else{
            return [];
          }        
        })
        .catch((err)=>{
          console.log('onPage Team error',err);
          return [];
        }); 
    }

    async function Get_data() {     
      setProcessing(true);
      try {   
        await db.transaction(async (txn) => {        
          let query1 = `
            SELECT DISTINCT s.*, IFNULL(h.Status , '') AS STATUS
            FROM Sup_ImageAuditStoreList s
            LEFT JOIN IMAGE_AUDIT_HDR_DATA h 
            ON s.MID = h.MID AND s.StoreId = h.STORE_ID;
          `;
    
          let query2 = `SELECT * FROM IMAGE_AUDIT_HDR_DATA`;
    
          console.log(query1, "query1");
          console.log(query2, "query2");
    
          // First Query Execution
          txn.executeSql(query1, [], (txn, result) => {
            if (result.rows.length > 0) {
              let arr = [];
              for (let i = 0; i < result.rows.length; i++) {
                let data = result.rows.item(i);
                arr.push(data);
              }
              setAddStoreInfo(arr);
              setIsDataFound(true);
              setrerenderdata(prevState => !prevState);
            }
          }, (error) => { 
            console.log("Error while executing query1: ", error); 
          });
    
          // Second Query Execution
          txn.executeSql(query2, [], (txn, result) => {
            if (result.rows.length > 0) {
              let hdrData = [];
              for (let i = 0; i < result.rows.length; i++) {
                let data = result.rows.item(i);
                hdrData.push(data);
              }
              setHdrData(hdrData); // Store the data in a new state
            }
          }, (error) => { 
            console.log("Error while executing query2: ", error); 
          });
    
          setProcessing(false); // Mark processing as false after executing both queries
        });
      } catch (err) {
        console.log("Error in Get_data function: ", err);     
        setProcessing(false);     
      }        
    }
    


  async function Get_Status() {     
    setProcessing(true);
    try {   
     
      await db.transaction(async (txn) => {        
        let query = `SELECT DISTINCT s.MID, s.StoreId, h.Status FROM Sup_ImageAuditStoreList s
                    LEFT JOIN IMAGE_AUDIT_HDR_DATA h ON s.MID = h.MID AND s.StoreId = h.STORE_ID;` ;
  
        console.log(query , "query")
        
        txn.executeSql(query, [], (txn, result) => {
  
          if (result.rows.length > 0) {
            let arr = [];
            for (let i = 0; i < result.rows.length; i++) {
              let data = result.rows.item(i);
              arr.push(data);
            }
            // setAddStoreInfo(arr);
            // console.log(arr, "STTATTSTSUUUSS")
           
            setProcessing(false);
            // console.log(arr, "Image Audit Store list data statuss........");
            // setrerenderdata(prevState => !prevState);
          } else{
            setProcessing(false);
          }
        }, (error) => { 
          setProcessing(false);
          console.log("Error while executing SQL: ", error); 
        });
      });
    } catch (err) {
      console.log("Error in Get_data function: ", err);     
      setProcessing(false);     
    }        
  }

  const StoreItem = memo(({ item }) => (
    <TouchableOpacity style={customStyle.storel} key={item.StoreId} 
    disabled={item.STATUS == 'U'} 
    onPress={() => {
    if (item.STATUS !== 'U') {
    props.navigation.navigate('ImageAudit', {imageauditstoreData: item , selectedDate : selectedDate});
     }
    }}
    >
      <View style={customStyle.storel_card_outer}>
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item.StoreName}</Text>
          </View>
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{`${ST.StoreId}:`}</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
            </View>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{`${ST.StoreType}:`}</Text>
              <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{item.StoreType}</Text>
            </View>
          </View>

          <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
            <View style={customStyle.storel_code}>
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder, customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{`${ST.Address}:`}</Text>
                <Text style={customStyle.storel_codeText}>{item.Address}</Text>
              </View>
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{`${ST.CityName}:`}</Text>
                <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{item.CityName}</Text>
              </View>
            </View>
          </View>

          <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{`${ST.CoveredBy}:`}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.CoveredBy}</Text>
            </View>
          </View>

          <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10, customStyle.storel_usOp]}>
         
         
          <TouchableOpacity 
            style={customStyle.storel_usOpBtn}
            disabled={item.STATUS == 'U'}  
            onPress={() => {
              if (item.STATUS !== 'U') {
                props.navigation.navigate('ImageAudit', {imageauditstoreData: item , selectedDate : selectedDate});
              }
            }}
          >
              <Image
                style={{ height: 18, width: 18, resizeMode: 'contain', tintColor: PageTheme.$accent_color }}
                source={require('../assets/icons/audit/audit.png')}
              />
              <Text style={customStyle.storel_usOpBtnText}>{'Audit'}</Text>
            </TouchableOpacity>

            { item.STATUS=="P" &&
              <View style={[customStyle.storel_usCon]}> 
                  <Text style={[customStyle.storel_usText,{color:'red'}]}>{"Upload Pending"}</Text> 
              </View>
            }

            { item.STATUS=="U" &&
            <View style={[customStyle.storel_usCon]}> 
              <Ionicons name='checkmark-done-sharp' color='green' size={20}/> 
                <Text style={[customStyle.storel_usText,{color:'green'}]}>{ST.Uploaded}</Text> 
            </View>
          }



          </View>
        </View>
      </View>
    </TouchableOpacity>
  ));

  let minDate = new Date();
  minDate.setDate(minDate.getDate() - 7);

  console.log(addStoreInfo , "addStoreInfo")

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
      {processing && <CustomLoader fullHeight title={loaderTitle} />}
      <CustomHeader {...props} title={'Image Audit Store List'} />

      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 0 }}
        style={[customStyle.roundScrollWrapper]}
      >
        <View style={[customStyle.pageContentWrapper]}>


        <View style={[{flexDirection:'row',alignItems:'center', justifyContent:'space-between', marginHorizontal:20, borderColor:'#d3d3d3',borderWidth:1, padding:10,borderRadius:5}]}>
          <Text style={{color:'#000'}}>Select Date</Text>
            <TouchableOpacity  style={[customStyle.repoertDetailsPicker,{}]} onPress={showDatePicker}>
             <Fontisto name='date' size={20} color={'#31ab92'} />  
            </TouchableOpacity>                                   
        </View>

        <View style={{flexDirection:'row', alignItems:'center', justifyContent:'space-between',marginHorizontal:20,marginTop:5}}>
          {selectedDate && (<Text style={{ marginTop: 0,backgroundColor:'#eaf3fa', borderRadius:4, padding:12,fontWeight:20,color:'black' }}>Selected Date: {moment(selectedDate).format('MM/DD/YYYY')}</Text>)}
          <DateTimePickerModal minimumDate={minDate} maximumDate={new Date()} isVisible={isDatePickerVisible}  mode="date" onConfirm={handleConfirm}  onCancel={hideDatePicker} />

            {selectedDate &&
                <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{getDataselectedDate(selectedDate)}}>
                    <Text style={customStyle.addVisBtnText}>Go</Text>
                </TouchableOpacity>
            }
        </View>

          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          <View style={customStyle.storelist_parentwrap}>
            {!isDataFound && (
              <View style={customStyle.noDataCon}>
                <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
              </View>
            )}

            {addStoreInfo?.length > 0 && (
              <View style={[customStyle.storel_Con, { paddingBottom: 0 }]}>
                <FlatList
                  data={addStoreInfo}
                  style={customStyle.listcon}
                  initialNumToRender={4}
                  contentContainerStyle={customStyle.iteml_con}
                  renderItem={({ item }) => <StoreItem item={item} {...props} />}
                />
              </View>
            )}
          </View>
        </View>
      </LinearGradient>
    </Container>
  );
};

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