import { Alert, Animated, Keyboard, RefreshControl } from 'react-native';
import {
  TextInput,
  Button,
  PermissionsAndroid,
  StatusBar,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ScrollView,
  FlatList,
  Dimensions
} from 'react-native';

import {useNavigation,NavigationContainer,useIsFocused} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import AsyncStorage from '@react-native-async-storage/async-storage';
import { useCallback, useEffect, useState } from 'react';
import { width } from '@fortawesome/free-solid-svg-icons/faMugSaucer';
import { SelectList } from 'react-native-dropdown-select-list';
import { PDAM_API_URL, PERMIT_API_URL, PJU_API_URL } from '../../urlConfig';
import AwesomeAlert from 'react-native-awesome-alerts';
import NetInfo from "@react-native-community/netinfo";
import Moment from 'moment';
import RNFetchBlob from 'rn-fetch-blob';
import { MenuProvider } from 'react-native-popup-menu';
import {
    Menu,
    MenuOptions,
    MenuOption,
    MenuTrigger,
  } from 'react-native-popup-menu';
import React from 'react';
type sendListDataProps = {route: any,navigation: any};
function DraftPermit({route,navigation}: sendListDataProps) {
    const survey_Type = [
        {key:'PJU', value:'PJU'},
        {key:'PERMIT', value:'PERMIT'},
        {key:'PDAM', value:'PDAM'},
    ]
    const [selectedSurveyType, setselectedSurveyType] = useState("");
    const [refreshing, setRefreshing] = useState(false);
    const onRefresh = useCallback(() => {
        setLocalStorage([]);
        getDataPermit();
        setRefreshing(true);
        setTimeout(() => {
          setRefreshing(false);
        }, 2000);
    }, []);
    const [localStorage, setLocalStorage] = useState([]);
    const [filterData, setFilterData] = useState([]);
    const [surveyType, setSurveyType] = useState("");
    const [alertOffline, setAlertOffline] = useState(false);
    const [connected, setConnected] = useState(true)
    const storeData = async (value:any) => {
        // console.log("key",value.case_name)
        
        try {
            const jsonValue = JSON.stringify(value);
          await AsyncStorage.setItem(String(value.case_id)+" / "+String(value.case_name)+" / "+String(value.case_category)+" / "+"3PA-01"+" / "+String(value.case_risk),jsonValue);
        } catch (e) {
          // saving error
        }
    };
    const multiSet = async () => {
        const firstPair = [1, "value_1"]
        const secondPair = [2, "value_2"]
        try {
            const objCase1 = JSON.stringify({id:1,case_name:"test1"})
            const objCase2 = JSON.stringify({id:2,case_name:"test2"})
            await AsyncStorage.multiSet([["case_1",objCase1],["case_2",objCase2]])
        }   catch(e) {
          //save error
        }
      
        // console.log("Done.")
    };
    const deleteById = (name:string) => {
        setLocalStorage(oldValues => {
            return oldValues.filter((local_data:any) => local_data.company_name !== name)
        })
    };
    const removeValue = async (key:string) => {
        try {
            // console.log("keyDelete",key);
          await AsyncStorage.removeItem(key)
        //   await getCount();
        } catch(e) {
        }
    };
    const selectSurveyType = () => {
        // console.log(selectedSurveyType);
        if(selectedSurveyType==='PJU'){
            getDataPJU()
        }
        if(selectedSurveyType==='PDAM'){
            getDataPDAM()
        }
        if(selectedSurveyType==='PERMIT'){
            getDataPermit()
        }
    };
    const getDataPJU = async () => {
        setLocalStorage([])
        try {
            const jsonValue = await AsyncStorage.getAllKeys()
            // console.log("All Key",jsonValue)
                if(jsonValue.length != 0) {
                    jsonValue.map((item) => {
                        if(item != "USER_DATA" && item != "my-jwt"){
                            let splited = item.split(" / ");
                            const objectItem = {
                                pju_name:splited[0],
                                pju_type:splited[1],
                                installation_date:splited[2],
                                status:splited[3],
                                keterangan:splited[4],
                                long:splited[5],
                                lat:splited[6]
                            }
                            // console.log(objectItem);
                            
                            if(splited[7] === 'draftPJU'){
                                setLocalStorage(oldArray => [...oldArray,objectItem])
                            }
                        }
                    })
                }
        } catch (e) {
          // error reading value
        }
    };
    const getDataPDAM = async () => {
        setLocalStorage([])
        try {
            const jsonValue = await AsyncStorage.getAllKeys()
            // console.log("All Key",jsonValue.length)
            if(jsonValue.length != 0) {
                jsonValue.map((item) => {
                    if(item != "USER_DATA" && item != "my-jwt"){
                        let splited = item.split(" / ");
                        if(splited.length === 7){
                            const objectItem = {
                                pipe_name:splited[0],
                                pipe_type:splited[1],
                                installation_date:splited[2],
                                status:splited[3],
                                keterangan:splited[4],
                                geom:splited[5].split(",")
                            }
                            // console.log(objectItem);
                            
                            if(splited[6] === 'draftPDAM'){
                                setLocalStorage(oldArray => [...oldArray,objectItem])
                            }
                        }
                        
                    }
                })
            }
        } catch (error) {
            
        }
    };
    const getDataPermit = async () => {
        setLocalStorage([])
        try {
            const jsonValue = await AsyncStorage.getAllKeys()
            console.log("All Key",jsonValue)
            if(jsonValue.length != 0) {
                jsonValue.map((item) => {
                    if(item != "USER_DATA" && item != "my-jwt"){
                        let splited = item.split(" / ");
                        console.log(splited.length);
                        
                        if(splited.length === 5){
                            const objectItem = {
                                company_name:splited[0],
                                permit_status:splited[1],
                                location:splited[2],
                                geom:splited[3].split(",")
                            }
                            // console.log(objectItem);
                            
                            if(splited[4] === 'draftPermit'){
                                setLocalStorage(oldArray => [...oldArray,objectItem])
                            }
                        }
                        
                    }
                })
            }
        } catch (error) {
            
        }
    };
    const isFocused = useIsFocused();
    useEffect(() => {
        if(isFocused){
            getDataPermit();
            const unsubscribe = NetInfo.addEventListener((state) => {
                setConnected(state.isConnected!)
              });
              return () => {
                unsubscribe();
            };
        };
    },[isFocused])
    const [draftData, setDraftData] = useState(0);
    navigation.addListener('beforeRemove', (e:any)=> {
    });
    const [stringFilter,setStingFilter] = useState('')
    const handleSearch = (text:string) => {
        // console.log(text);
        
        const formattedQuery = text.toLowerCase();
        const filteredData = localStorage.filter(data =>
            data.case_name.toLowerCase().includes(formattedQuery)
        )
        setFilterData(filteredData)

    };
    const reSend = async (data:any) => {
        if(connected){
            if(selectedSurveyType==="PJU"){
                try {
                    const result = {
                        status: 0,
                        body: {},
                    }
                    await RNFetchBlob.config({
                        trusty : true
                    }).fetch('POST', `${PJU_API_URL}/addData`,{
                        "Accept": 'application/json',
                        "Content-Type": "application/json",
                        },
                        JSON.stringify({
                            nama: data.nama,
                            jenis: data.jenis,
                            tanggal_installasi: data.date,
                            status: data.status,
                            keterangan: data.keterangan,
                            geom: `POINT(${data.long} ${data.lat})`
                        })
                    ).then(async (resp) => {
                        const status = resp.respInfo.status
                        if (status == 201) {
                            deleteById(data.nama);
                            removeValue(data.nama+" / "+data.jenis+" / "+data.date+" / "+data.status+" / "+data.keterangan+" / "+data.long+" / "+data.lat+" / draftPJU");
                        }
                        else {
                            Alert.alert("Internal Server Error")
                        }
                    })
                } catch (error) {
                    Alert.alert("Internal Server Error")
                }
            }
            if(selectedSurveyType==="PDAM"){
                try {
                    const obj = {
                        nama: data.nama,
                        jenis: data.jenis,
                        tanggal_installasi: data.date,
                        status: data.status,
                        keterangan: data.keterangan,
                        geom: `MULTILINESTRING((${data.geom}))`
                    };
                    await RNFetchBlob.config({
                        trusty : true
                    }).fetch('POST', `${PDAM_API_URL}/addData`,{
                        "Content-Type": "application/json",
                        },
                        JSON.stringify(obj)
                    ).then(async(resp) => {
                        const json = resp.json();
                        const status = resp.respInfo.status
                        if (status == 201) {
                            deleteById(data.nama);
                            removeValue(data.nama+" / "+data.jenis+" / "+data.date+" / "+data.status+" / "+data.keterangan+" / "+data.geom+" / draftPDAM");
                        }
                        else {
                            Alert.alert("Internal Server Error")
                        }
                    })
                } catch (error) {
                    Alert.alert("Internal Server Error");
                }
                
            }
            if(selectedSurveyType==="PERMIT"){
                try {
                    const obj = {
                        company_name: data.company_name,
                        location: data.location,
                        permit_status: data.permit_status,
                        geom: `MULTIPOLYGON (((${data.geom},${String(data.geom).split(",")[0]})))`
                    }
                    await RNFetchBlob.config({
                        trusty : true
                    }).fetch('POST', `${PERMIT_API_URL}/addData`,{
                        "Content-Type": "application/json",
                        },
                        JSON.stringify(obj)
                    ).then(async(resp) => {
                        const json = await resp.json();
                        const status = resp.respInfo.status;
                        if (status == 201) {
                            deleteById(data.company_name);
                            removeValue(data.company_name+" / "+data.permit_status+" / "+data.location+" / "+data.geom+" / draftPermit");
                        }
                        else {
                            Alert.alert("Internal Server Error")
                        }
                    }) 
                } catch (error) {
                    Alert.alert("Internal Server Error")
                }
                
            }
        }
        else{
            setAlertOffline(true)
        }
    };
    const optionsStyles = {
        optionsContainer: {
            alignItems: 'flex-start',
            justifyContent: 'center',
            width:100,
            marginVertical:-10,
            marginLeft:-10,
            backgroundColor: '#FFFFFF',
            borderRadius: 5,
            shadowColor: '#00000040',
            shadowOffset: {
                width: 0,
                height: 2,
            },
            borderColor:'#6B5E5E4D',
            borderWidth:1,
            shadowOpacity: 0.2,
            shadowRadius: 6,
            elevation: 5,
        },
        optionText: {
          color: 'brown',
        },
    };
    return(
        <View style={styles.mainContainer}>
            <StatusBar backgroundColor="#34A6F8" barStyle={'light-content'} />
            <View key={"mainBackground"} style={{backgroundColor:'#34A6F8',width:'100%',height:'93%'}} />
            <View key={"background"} style={{backgroundColor:'#FFFFFF',width:'100%',height:'100%',position:'absolute',borderTopRightRadius:50,borderTopLeftRadius:35,marginTop:10}}>
                <View key={"Filter"} style={{paddingLeft:30,paddingTop:30,paddingRight:30,marginTop:10}}>
                    <TextInput
                        style={{
                            height: 40,
                            padding: 10,
                            borderRadius: 50,
                            color: 'black',
                            backgroundColor:'#e6e3e3'
                        }}
                        inlineImageLeft="search"
                        inlineImagePadding={20}
                        placeholderTextColor={'#6B5E5E'}
                        placeholder='Search'
                        onChangeText={queryText => {handleSearch(queryText),setStingFilter(queryText)}}
                        defaultValue={stringFilter}
                    />
                </View>
                <ScrollView 
                    style={{
                        padding: 30
                    }}
                    refreshControl={
                        <RefreshControl refreshing={refreshing} />
                    }
                >
                    { 
                        localStorage.length != 0 ? 
                        localStorage.map((item:any,index:number) => (
                        <View key={index}>
                            <View style={{flexDirection:'row'}}>
                                <View style={{ flexDirection:'column',paddingLeft:0,width:'35%'}}>
                                    <Text style={{fontSize:14,color:'#000000',fontWeight:'600',padding:5}}>Company Name</Text>
                                    <Text style={{fontSize:14,color:'#000000',fontWeight:'600',padding:5}}>Permit Status</Text>
                                    <Text style={{fontSize:14,color:'#000000',fontWeight:'600',padding:5}}>Location</Text>
                                </View>
                                <View style={{ flexDirection:'column',paddingLeft:0,width:'65%'}}>
                                    <Text style={{fontSize:14,fontWeight:'400',color:'#000000',padding:5}}>: {item.company_name}</Text>
                                    <Text style={{fontSize:14,fontWeight:'400',color:'#000000',padding:5}}>: {item.permit_status}</Text>
                                    <Text style={{fontSize:14,fontWeight:'400',color:'#000000',padding:5}}>: {item.location}</Text>
                                </View>
                                <View style={{ marginLeft:'55%',marginTop:0,width:150,height:100,position:'absolute'}}>
                                    <MenuProvider skipInstanceCheck={true} style={{flexDirection:'column'}}>
                                        <Menu>
                                            <MenuTrigger>
                                                <Image
                                                    style={{justifyContent:'center',alignSelf:'flex-end'}}
                                                    source={require('../../assets/icon/Actions.png')}
                                                    resizeMode='cover'
                                                />
                                            </MenuTrigger>
                                            <MenuOptions customStyles={optionsStyles}>
                                                <MenuOption
                                                    onSelect={()=>{
                                                        navigation.navigate('Permit Editing',{ screen: 'Edit',data: {
                                                            id:item.id,
                                                            company_name:item.company_name,
                                                            permit_status:item.permit_status,
                                                            location:item.location,
                                                        }});
                                                    }}
                                                    children={
                                                        <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
                                                            <Image source={require('../../assets/icon/edit.png')} />
                                                            <Text style={{marginLeft:10,color:'#6B5E5EB2',fontSize:14,fontWeight:400}}>Edit</Text>
                                                        </View>} 
                                                />
                                                <View style={{marginVertical: 5, width:85,
                                                marginHorizontal: 2,
                                                borderBottomWidth: 1,
                                                borderColor: '#ccc'}}
                                                />
                                                <MenuOption
                                                    onSelect={()=> {
                                                        deleteById(item.company_name);
                                                        removeValue(item.company_name+" / "+item.permit_status+" / "+item.location+" / "+item.geom+" / draftPermit");
                                                    }}
                                                    children={
                                                        <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
                                                            <Image source={require('../../assets/icon/dell.png')} />
                                                            <Text style={{marginLeft:10,color:'#6B5E5EB2',fontSize:14,fontWeight:400}}>Delete</Text>
                                                        </View>
                                                    }
                                                />
                                            </MenuOptions>
                                        </Menu>
                                    </MenuProvider>
                                </View>
                            </View>
                            <View
                                style={{
                                    marginTop: 10,
                                    marginBottom: 10,
                                    borderBottomColor: '#E2E2E2',
                                    borderBottomWidth: 2,
                                }}
                            />
                            </View> 
                            ))
                        :
                        <View style={{alignItems:'center',padding:20}}>
                            <Text style={{fontSize:16,color:'grey'}}>Data Kosong</Text>
                        </View>
                    }
                    
                </ScrollView>
            </View>
            <AwesomeAlert
                show={alertOffline}
                showProgress={false}
                title="You are offline"
                message="You need connection for Resend Data."
                closeOnTouchOutside={false}
                closeOnHardwareBackPress={false}
                showConfirmButton={true}
                confirmText="Ok"
                confirmButtonColor="#DD6B55"
                onConfirmPressed={() => {
                    setAlertOffline(false);
                }}
                overlayStyle={{width:'100%'}}
                contentContainerStyle={{width:'70%',borderRadius:10}}
                titleStyle={{fontSize:20}}
                messageStyle={{fontSize:16}}
            />
            {/* <Button onPress={getDataAll} title='GetDataByKey'/> */}
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ecf0f1',
        padding: 10,
      },
    mainContainer: {
        flex: 1,
    },
    title: {
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        fontWeight: 'bold',
        fontSize: 22,
        color: 'black',
        marginBottom: 10
    },
    input: {
        height: 40,
        borderWidth: 1,
        padding: 10,
        borderRadius: 50,
        color: 'black'
    },
});

export default DraftPermit;