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, Keyboard} 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, UploadData2, validateNumber} 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, 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 { CustomPicker2 } from '../components/CustomPicker';
import { ConfirmSaveAlert } from '../components/alert';

function WarehouseinwardDetail(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};

    const { item,ChallanTypeId,isDisable } = route.params;
    const screenWidth = Dimensions.get('window').width;
  
    // 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 [keysList, setKeysList] = useState([]);

    const [rerenderdata, setrerenderdata]= useState(0);
    
    const [NodataFound, setNodataFound] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [reasons_list, setReasons_list] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [InwardQuantity, setInwardQuantity] = useState(0);
    const [ActualQuantity, setActualQuantity] = useState(0);

    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 q3=`Select * From Master_WarehouseReason `;
                await txn.executeSql(q3,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                setReasons_list(arr);
                            }                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                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.Id,wi.ItemId, wi.ItemName, wi.ItemCode, wi.InwardQty,st.DAMAGE_QTY as DamageQuantity,st.CONFIRM_QTY as ConfirmQuantity,st.REASON as Reason,st.REASON_ID as ReasonId,st.REMARK as Remark FROM Warehouse_InwardData wi ${join} WHERE ChallanTypeId='${ChallanTypeId}'`;

                await txn.executeSql(query, [], async function (txn2, txnres) { 
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        let InwardQtyVal=0;
                        let ActualQty=0;
                        for (let i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);

                            data["ConfirmQuantity"]=data?.ConfirmQuantity || data?.InwardQty ||"0"
                            data["DamageQuantity"]=(data?.DamageQuantity===0||data?.DamageQuantity==="0")?"0":data?.DamageQuantity
                            arr.push(data);
                            InwardQtyVal=InwardQtyVal+(data?.InwardQty||0)
                            ActualQty=ActualQty+Number(data?.ConfirmQuantity||0)+Number(data?.DamageQuantity||0)
                        }
                        setInwardQuantity(InwardQtyVal)
                        setActualQuantity(ActualQty)

                        const keys = arr.length > 0 ? Object.keys(arr[0]).filter(key => ((key !== 'ItemId')&& (key !=='DamageQuantity') && (key !== 'ConfirmQuantity') && (key !== 'Reason') && (key !=='Id') && (key !=="ReasonId") && (key !=="Remark"))) : [];

                        setKeysList(keys)
                        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 onChange(val,key,type="",index){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        let wareHList= WarehouseInwardData
        let wareHobj=wareHList[index]
        wareHobj[key]=val;
        wareHList[index]=wareHobj
        setWarehouseInwardData([...wareHList]);
        // setrerenderdata(!rerenderdata);
    }

    function onselectionChange3(option, keyLbl, keyVal, otherData){
        let wareHList= WarehouseInwardData
        let wareHobj=wareHList[otherData?.index]
        wareHobj[keyLbl]=option?.label;
        wareHobj[keyVal]=option?.value;
        wareHList[otherData?.index]=wareHobj
        setWarehouseInwardData([...wareHList]);
        // setrerenderdata(!rerenderdata);
    }


    async function validate() {
        let isValid = true;

        // function showError(obj, isErr) {
        //   setErrorField(obj);
        //   setError(isErr);
        // }
    
        return new Promise((resolve, reject) => {
          for (const wObj of WarehouseInwardData) {          
    
            // let errorobj = { EF_Window: window };
                if (!wObj?.ConfirmQuantity) {
                //   errorobj["EF_NExistReason"] = "NExistReason";
                //   showError(errorobj, true);
                  notify(`Please fill Confirm Quantity of ${wObj?.ItemName}`, "LONG");
                  resolve(false);
                  return;
                }
                else if(!wObj?.DamageQuantity){
                    notify(`Please fill Damage Quantity of ${wObj?.ItemName}`,'LONG');
                    resolve(false);return;
                }else if((((Number(wObj?.ConfirmQuantity) || 0)+(Number(wObj?.DamageQuantity) || 0)) < Number(wObj.InwardQty)) && !wObj?.Reason ){
                    notify(`Please select Reason of ${wObj?.ItemName}`,'LONG');
                    resolve(false);return;
                }
                 
          }
          
            resolve(true);
            return;
          
        })
          .then((val) => {
            return val;
          })
          .catch((err) => {
            console.log(err);
            return false;
          });
      }

      function onSaveCancel() {
        setShowAlert(false);
      }

    async function onSubmitData() {
        let isvalid = await validate();
    
        if (isvalid) {
          Keyboard.dismiss();
          setShowAlert(true);
        }
      }

      async function uploadData(){

        setShowAlert(false);
        setLoaderTitle(ST.SavingData + "...");
        setProcessing(true);

        const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
        console.log('pdurl',url)
        
        let payload = WarehouseInwardData.map((item)=>{
            let obj= {
                ...item,
                Reason: item?.Reason ||"",
                ChallanTypeId: ChallanTypeId,
                ReasonId: item?.ReasonId || 0,
                Remark: item.Remark||"",
                UserId: props.UserId
            }
            delete obj['ItemName']
            return obj;
        })

        let postData={
        'MID':0,
        'Keys':'WareHouseInWard',
        'JsonData':JSON.stringify(payload),
        'UserId':props.UserId,};
    
        console.log('postData',postData)
         UploadData2(url,postData)
        .then(async(res)=>{
          console.log('res:',res);
          if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
                   
            saveData()
            // let isUpdated=await updateVLUploadStatus();
            // if(isUpdated){
            //     notify('Uploaded successfully');
            // }
          
            
          }else{
            setProcessing(false);
            notify('Cannot upload Ware House Inward data');
          }
        })
        .catch((err)=>{
            console.log(err);
            setProcessing(false);
            notify('Cannot upload Ware House Inward data');
        }); 
    
      }

      async function saveData() {
        // setHasUnsavedChanges(false);
        // BgUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + "...");
        setProcessing(true);
        let d1n = new Date();
        let d3 = moment(d1n).format("MM/DD/YYYY");
        try {
    
          let q3=`DELETE FROM ${AppTables.WARE_HOUSE_INWARD} WHERE CHALLAN_TYPE_ID='${ChallanTypeId}' and VISIT_DATE='${d2}' `;
              
          
          await db.transaction(async function (txn) {
            // add data
            var values = "";

            await txn.executeSql(q3,[],async function (txn2, txnres) { 
                console.log('WARE_HOUSE_INWARD data deleted');
            },function (txnE,txnerr) { console.log(txnerr); });
      
    
            for (const warObj of WarehouseInwardData) {
                const {ItemId,ItemName,ItemCode,InwardQty,ConfirmQuantity,DamageQuantity,Reason,ReasonId, Remark }=warObj;

                values += values != "" ? " , " : "";
                values += `('${ItemId}','${ItemName}','${ItemCode}','${InwardQty}','${ConfirmQuantity}','${DamageQuantity}','${Reason||""}','${ReasonId||""}','${ChallanTypeId}','${d2}','${Remark||""}')`;
            }
    
            console.log("values:", values);
    
            let add_hdr_data = `INSERT INTO ${AppTables.WARE_HOUSE_INWARD} (ITEMID , ITEMNAME, ITEM_CODE, IN_WARD_QTY , CONFIRM_QTY, DAMAGE_QTY , REASON, REASON_ID, CHALLAN_TYPE_ID,VISIT_DATE,REMARK) VALUES ${values} `;
        
            await txn.executeSql(
              add_hdr_data,
              [],
              async function (txn2, txnres) {
                console.log("WARE_HOUSE_INWARD data added");
               
                //   clear_item("storeData");
                  setProcessing(false);
                  notify("warehouse updated successfully");
                  props.navigation.goBack();

              },
              function (txnE, txnerr) {
                console.log(txnerr);
                setProcessing(false);
                notify("Cannot add warehouse data");
              }
            );
          });
        } catch (err) {
          console.log(err);
        }
      }
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={'Warehouse Inward Detail'}/>
        {ConfirmSaveAlert(props, showAlert, onSaveCancel, uploadData)}
        <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', width : '104%', justifyContent:'space-between', paddingHorizontal:10}}>
          <View style={[customStyle.STp_hdrParent, {width : '60%', paddingHorizontal:0}]}>
          <View  style={[customStyle.STp_Hdr, {width : '60%'}]}>
              <Text style={customStyle.STp_HdrText}>Actual Qty : {ActualQuantity}</Text>
          </View>
          </View> 

          <View style={[customStyle.STp_hdrParent, {width : '60%',  paddingHorizontal:0}]}>
            <View  style={[customStyle.STp_Hdr, {width : '60%'}]}>
                <Text style={customStyle.STp_HdrText}>Inward Qty : {InwardQuantity}</Text>
            </View>
          </View> 
          </View>

            <ScrollView contentContainerStyle={{ paddingBottom: 100 }}>
            <View style={[style.reportCon, { width: screenWidth }]}>
            <FlatList 
            data={WarehouseInwardData}
            // extraData={rerenderdata}
            renderItem={({item,index})=>{
                return(
                        <View style={[style.cardContainer, (index % 2 !== 0 ? customStyle.reportItemBg : {})]}>
                            <View style={style.card}>
                                {keysList.map((key, keyIndex) => (
                                    <View key={keyIndex} style={style.cardRow}>
                                        <View style={style.cardKey}>
                                            <Text style={style.cardKeyText}>{key}</Text>
                                        </View>
                                        <View style={style.cardValue}>
                                            <Text style={style.cardValueText}>{item[key]}</Text>
                                        </View>
                                    </View>
                                ))}

                                <View style={[customStyle.addVisCol100, {marginTop :10}]}>
                                <View style={[customStyle.addVisFormGrp,{flexDirection:"row",alignItems :'center'}]}>
                                    <Text style={[customStyle.addVisLabel, { flex: 0.6}]}>{"Received Qty"}</Text>
                                    <TextInput  
                                    style={[customStyle.addVisInputStyle,{width : '50%'},(isDisable && {backgroundColor:"#cccfd1"})]} 
                                    autoComplete='off'
                                    maxLength={10}
                                    keyboardType='numeric'
                                    editable={!isDisable}
                                    defaultValue={String(item?.ConfirmQuantity || "")}
                                    // value={String((item.ConfirmQuantity) || '')}
                                    // value={String((item.ConfirmQuantity==0?"0":item.ConfirmQuantity) || '')}
                                    onChangeText={(val)=>{((Number(item.DamageQuantity||0)+Number(val))<= item.InwardQty) && onChange(val,'ConfirmQuantity','numeric',index)}}
                                    />
                                </View>
                            </View>
                            <View style={[customStyle.addVisCol100, {marginTop :0}]}>
                            <View style={[customStyle.addVisFormGrp,{flexDirection:"row",alignItems :'center'}]}>
                                <Text style={[customStyle.addVisLabel, { flex: 0.6}]}>{"Damage Qty"}</Text>
                                <TextInput  
                                style={[customStyle.addVisInputStyle,{width : '50%'},(isDisable && {backgroundColor:"#cccfd1"})]} 
                                autoComplete='off'
                                maxLength={10}
                                keyboardType='numeric'
                                editable={!isDisable}
                                // value={String((item.DamageQuantity==0?"0":item.DamageQuantity) || '')}
                                value={String((item.DamageQuantity) || '')}
                                onChangeText={(val)=>{((Number(item.ConfirmQuantity||0)+Number(val))<= item.InwardQty) && onChange(val,'DamageQuantity','text',index);}}
                                />
                            </View>

                            { item?.ConfirmQuantity && (item?.DamageQuantity!="") && ((Number(item?.ConfirmQuantity) || 0)+(Number(item?.DamageQuantity) || 0)!=0) &&  (Number(item?.ConfirmQuantity) || 0)+(Number(item?.DamageQuantity) || 0) < item.InwardQty && 
                            <View style={[customStyle.openStk_prd_colflex, customStyle.pt10, customStyle.mb10]}>
                                <Text style={[customStyle.openStk_prd_label,  { flex: 0.6,marginRight:50 }]}>{"Select Reason"}</Text>

                                {
                                <CustomPicker2
                                    {...props}
                                    Pickerdata={reasons_list}
                                    label_key={"Reason"}
                                    value_key={"ReasonId"}
                                    onchangeKeyLbl={"Reason"}
                                    onchangeKey={"ReasonId"}
                                    onChange={onselectionChange3}
                                    selected_data={{
                                      value: item?.Reason||"",
                                      otherData: { index,item },
                                    }}
                                    isDisable={isDisable}
                                    InputStyle={[customStyle.PV_selectInputStyle,{backgroundColor:isDisable?"#cccfd1":'#e5f3ff'},{width:"82%"}]}
                                    selectStyle={[customStyle.PV_selectStyle]}
                                    // ErrorStyle={EStyle_NExistReason}
                                    // ShowError={error}
                                />
                                }
                            </View>
                            }
                            <View style={[customStyle.addVisCol100, {marginTop :10}]}>
                                <View style={[customStyle.addVisFormGrp,{flexDirection:"row",alignItems :'center'}]}>
                                    <Text style={[customStyle.addVisLabel, { flex: 0.6}]}>{"Remark"}</Text>
                                    <TextInput  
                                    style={[customStyle.addVisInputStyle,{width : '50%'},(isDisable && {backgroundColor:"#cccfd1"})]} 
                                    editable={!isDisable}
                                    autoComplete='off'
                                    maxLength={10}
                                    keyboardType='text'
                                    value={item.Remark || ''}
                                    onChangeText={(val)=>{onChange(val,'Remark','text',index);}}
                                    />
                                </View>
                            </View>
                        </View>
                            </View>
                        </View>
                    )}}
                />
            </View>
        </ScrollView>

          <View style={{alignItems:'center', paddingBottom:20, paddingTop:-20}} >
           <GradientButton {...props} title={'Save'} onPress={onSubmitData} disabled={isDisable||false} colors={isDisable?[PageTheme.$tertiary_color,PageTheme.$tertiary_color]:null}/>
         </View>
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

const style = StyleSheet.create({
    reportCon: {
        padding: 10,
    },
    cardContainer: {
        marginBottom: 10,
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 10,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 2,
        elevation: 2,
        marginBottom: 10,
        padding: 10,
    },
    cardRow: {
        flexDirection: 'row',
        paddingVertical: 3,
        //  backgroundColor:'red'
    },
    cardKey: {
        flex: 0.4,
        // width:'40%'
    },
    cardKeyText: {
        color :'#333333'
    },
    cardValue: {
        flex: 0.90,
        // width:'60%'
    },
    cardValueText: {
        color: '#000',
        fontWeight:'500'
    },
    reportItemBg: {
        backgroundColor: '#f1f1f1',
    },
});



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


  