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,KeyboardAvoidingView, Alert, StyleSheet, Dimensions} 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 {getDownloadJson,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, DataTable, Menu, Switch} from 'react-native-paper';
import {AntDesign, Ionicons, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { getMethodName, METHODS } from '../constants/methodNames';
import { getPostData, getPostData2 } from '../components/downloadTasks';
import NoDataComponent from '../components/NoDataComponent';

function Warehouseinward(props) { 
    const route = useRoute();
  
    // 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 [AllWarehouses, setAllWarehouses] = useState([]);
    const [WarehouseInwardData, setWarehouseInwardData] = useState([]);

    const [rerenderdata, setrerenderdata]= useState(0);
    
    const [NodataFound, setNodataFound] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        
       getData();
       const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
       const willFocusSubscription = props.navigation.addListener('focus', () => {
        getData();
      });

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

    useEffect(() => {
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    function  onBeforeRemove(e){
        if (hasUnsavedChanges==true) {
            e.preventDefault(); // Prevent default behavior of leaving the screen
            onRemoveScreen(e);
        }
        else{
           return;
        }   
    }
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    async function getData() {
        try {   
            let token = await get_item('loginToken');
            let loginInfo = await get_item('loginInfo');
            const loginDetails = JSON.parse(loginInfo);
            let desg = loginDetails.Designation || '';
    
            await db.transaction(async function (txn) {     
                let join=` Left Outer Join ${AppTables.WARE_HOUSE_INWARD} st on st.ITEMID=wi.ItemId and st.CHALLAN_TYPE_ID=wi.ChallanTypeId and st.VISIT_DATE='${d2}'`   
                let query = `SELECT DISTINCT wi.ChallanTypeId, wi.ChallanNo, wi.ChallanType, wi.ChallanDate, SUM(wi.InwardQty) AS InwardQty, wi.ConfirmQty, COUNT(st.ITEM_CODE) As CONFIRM_QTY, COUNT(*) AS TotalLines FROM Warehouse_InwardData wi ${join} GROUP BY ChallanTypeId`;
                await txn.executeSql(query, [], async function (txn2, txnres) { 
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        for (let i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            arr.push(data);
                        }
                        setLoaderTitle(false);
                        setProcessing(false);
                        setWarehouseInwardData(arr);
                        setrerenderdata(!rerenderdata);
                    } else {
                        setNodataFound(true);
                        setLoaderTitle(false);
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { 
                    console.log(txnerr);
                    setLoaderTitle(false);
                    setProcessing(false);     
                });
            });          
        } catch (err) {
            console.log(err);     
            setLoaderTitle(false);
            setProcessing(false);     
        }        
    }
    

    function gotoPage(item){
    
    }

    function _renderWarehouses() {
        const screenWidth = Dimensions.get('window').width;
        // Define which keys should appear in each row
        const firstRowKeys = ["ChallanNo"];
        const secondRowKeys = ["ChallanType", "ChallanDate"];
        const thirdRowKeys = ["InwardQty", "ConfirmQty", "TotalLines"];
    
        return (
            <ScrollView contentContainerStyle={{ paddingBottom: 100 }}>
                <View style={[style.reportCon, { width: screenWidth }]}>
                    {WarehouseInwardData.length > 0 && WarehouseInwardData.map((item, index) => (
                        <TouchableOpacity
                            key={index}
                            activeOpacity={0.9}
                            onPress={() => props.navigation.navigate('WareHouseInwardDetail', { ...item, ChallanTypeId: item.ChallanTypeId, isDisable: item.CONFIRM_QTY == item.TotalLines })} // Pass the entire item object including ChallanTypeId
                        >
                            <View style={[style.cardContainer, (index % 2 !== 0 ? customStyle.reportItemBg : {})]}>
                                <View style={style.card}>
                                    <View style={style.cardRow}>
                                        {firstRowKeys.map((key, keyIndex) => (
                                            <React.Fragment key={keyIndex}>
                                                <View style={style.cardKey}>
                                                    <Text style={style.cardKeyText}>{key}</Text>
                                                </View>
                                                <View style={style.cardValue}>
                                                    <Text style={style.cardValueText}>{item[key]}</Text>
                                                </View>
                                            </React.Fragment>
                                        ))}
                                    </View>
                                    <View style={style.horizontalLine} />
                                    {/* Second row */}
                                    <View style={style.cardRow2}>
                                        {secondRowKeys.map((key, keyIndex) => (
                                            <React.Fragment key={keyIndex}>
                                                <View style={style.cardKey2}>
                                                    <Text style={style.cardKeyText}>{key}</Text>
                                                    <Text style={style.cardValueText}>{item[key]}</Text>
                                                </View>
                                            </React.Fragment>
                                        ))}
                                    </View>
                                    <View style={style.horizontalLine} />
                                    <View style={style.cardRow3}>
                                        {thirdRowKeys.map((key, keyIndex) => (
                                            <React.Fragment key={keyIndex}>
                                                <View style={style.cardKey}>
                                                    <Text style={style.cardKeyText}>{key}</Text>
                                                    <Text style={style.cardValueText}>{item[key=="ConfirmQty"?"CONFIRM_QTY" :key]}</Text>
                                                </View>
                                            </React.Fragment>
                                        ))}
                                    </View>
                                    {item.CONFIRM_QTY == item.TotalLines &&
                                        <View style={[customStyle.storel_usCon]}>
                                            <Ionicons name='checkmark-done-sharp' color='green' size={20} />
                                            <Text style={[customStyle.storel_usText, { color: 'green' }]}>{"Uploaded"}</Text>
                                        </View>
                                    }
                                </View>
                            </View>
                        </TouchableOpacity>
                    ))}
                </View>
            </ScrollView>
        );
    }
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={'Warehouse Inward'}/>
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper]}>
          <View style={[customStyle.pageContentWrapper, {paddingTop:0}]}>
            {/* <View style={customStyle.warehouseHd}>
                <Text  style={customStyle.warehouseHdText}>Warehouses</Text>
            </View> */}
            { WarehouseInwardData.length==0 && <NoDataComponent {...props}/>}
            { Object.keys(WarehouseInwardData).length>0 &&
                _renderWarehouses(WarehouseInwardData)
            }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

const style = StyleSheet.create({
    reportCon: {
        padding: 10,
    },
    cardContainer: {
        marginBottom: 10,
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 10,
        // borderWidth:0.5,
        // borderColor:"grey",
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 2,
        elevation: 2,
        marginBottom: 10,
        padding: 15,
    },
    cardRow: {
        paddingVertical: 5,
    },
    cardRow2:{
    flexDirection: 'row',
    paddingVertical: 5,
    justifyContent:'space-between',
    },
    cardRow3:{
    flexDirection: 'row',
    paddingVertical: 5,
    justifyContent:'space-between',
   
    },
    cardKey: {
        // flex: 1,
        // width:'120%'
    },
    cardKey2: {
        flex: 1,
        // width:'120%'
    },
    cardKeyText: {
        color :'#707070',
        // fontWeight: '500',
    },
    cardValue: {
        flex: 1,
    },
    cardValueText: {
        color: '#141414',
        fontWeight: '500',
    },
    reportItemBg: {
        backgroundColor: '#f1f1f1',
    },
   horizontalLine: {
    height: 1, 
    backgroundColor: '#D3D3d3', 
    width: '100%', 
  },
});



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


  