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 AsyncStorage from '@react-native-async-storage/async-storage';
import {useNavigation,NavigationContainer,useIsFocused} from '@react-navigation/native';
import { useCallback, useEffect, useState } from 'react';
import { SelectList } from 'react-native-dropdown-select-list';
import AwesomeAlert from 'react-native-awesome-alerts';
import NetInfo from "@react-native-community/netinfo";
import { PJU_API_URL } from '../../urlConfig';
type sendListDataProps = {route: any,navigation: any};
function SentListScreen({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(() => {
        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) => {
        if(selectedSurveyType==="PJU"){
            setLocalStorage(oldValues => {
                return oldValues.filter((local_data:any) => local_data.pju_name !== name)
            })
        }
        if(selectedSurveyType==="PDAM"){
            setLocalStorage(oldValues => {
                return oldValues.filter((local_data:any) => local_data.pipe_name !== name)
            })
        }
        if(selectedSurveyType==="PERMIT"){
            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 getDataPDAM = 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(" / ");
                        if(splited.length === 8){
                            const objectItem = {
                                id:splited[0],
                                pipe_name:splited[1],
                                pipe_type:splited[2],
                                installation_date:splited[3],
                                status:splited[4],
                                keterangan:splited[5],
                                geom:splited[6].split(",")
                            }
                            console.log(objectItem);
                            
                            if(splited[7] === 'sentPDAM'){
                                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(" / ");
                        if(splited.length === 6){
                            const objectItem = {
                                id:splited[0],
                                company_name:splited[1],
                                permit_status:splited[2],
                                location:splited[3],
                                geom:splited[4].split(",")
                            }
                            console.log("aaa",objectItem);
                            
                            if(splited[5] === 'sentPermit'){
                                setLocalStorage(oldArray => [...oldArray,objectItem])
                            }
                        }
                        
                    }
                })
            }
        } catch (error) {
            
        }
        
    }
    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 = {
                                id:splited[0],
                                pju_name:splited[1],
                                pju_type:splited[2],
                                installation_date:splited[3],
                                status:splited[4],
                                keterangan:splited[5],
                                long:splited[6],
                                lat:splited[7]
                            }
                            
                            if(splited[8] === 'sentPJU'){
                                setLocalStorage(oldArray => [...oldArray,objectItem])
                            }
                        }
                    })
                }
        } catch (e) {
          // error reading value
        }
    };
    const isFocused = useIsFocused();
    useEffect(() => {
        if(isFocused){
            // getData()
            // .catch(console.error);
            const unsubscribe = NetInfo.addEventListener((state) => {
                setConnected(state.isConnected!)
              });
              return () => {
                unsubscribe();
            };
        };
    },[isFocused])
    const [draftData, setDraftData] = useState(0);
    navigation.addListener('beforeRemove', (e:any)=> {
        // Alert.alert(String(draftData))
        
        // route.params.onGoBack(draftData);
    })
    const getCount = async () => {
        try {
          const jsonValue = await AsyncStorage.getAllKeys()
          let index = 0;
          jsonValue.map((item) => {
            if(item != "USER_DATA" && item != "my-jwt"){
                let splited = item.split(" / ");
                if(splited[4] === 'draftPJU'){
                    index+=1
                }
            }
            setDraftData(index)
        })
        } catch (e) {
        }
    };
    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 getDataAll = async () => {
        try {
          const jsonValue = await AsyncStorage.getAllKeys()
        console.log("All",jsonValue)
        //   return jsonValue != null ? JSON.parse(jsonValue) : null;
        } catch (e) {
          // error reading value
        }
    };
    const getDataItem = async () => {
        try {
          const jsonValue = await AsyncStorage.getItem("120 / test1 / Structure Damage Missing / SDM-1 / 1. High")
          console.log("pure",jsonValue)
          return jsonValue != null ? JSON.parse(jsonValue) : null;
        } catch (e) {
          // error reading value
        }
    };
    const getMultiple = async () => {
        try {
        await AsyncStorage.removeItem("141 / Case 1 / Structure Damage Missing / SDM-01 / 2. Medium / draft")
        } catch(e) {
        }
    }
    const reSend = async (data:any) => {
        if(connected){
            let result = await fetch(`${PJU_API_URL}/addData`, {
                method: "POST",
                headers: {
                  "Content-Type": "application/json"
                },
                body: JSON.stringify({
                  nama: data.nama,
                  jenis: data.jenis,
                  tanggal_installasi: data.date,
                  status: data.status,
                  keterangan: data.keterangan,
                  geom: `POINT(${data.long} ${data.lat})`
                })
            });
            const status = result.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")
            }
          }
          else{
            setAlertOffline(true)
        }
    }
    const gotoEdit = () => {
        
    }
    return(
        <View style={styles.mainContainer}>
            <SelectList
                search={false}
                placeholder="Select Survey Type"
                boxStyles={{borderRadius:50,borderWidth:2,borderColor:'black'}}
                inputStyles={{color:'black'}}
                dropdownTextStyles={{color:'black'}}
                data={survey_Type}
                setSelected={setselectedSurveyType}
                onSelect={selectSurveyType}
            />
            <ScrollView style={styles.container}
            refreshControl={
                <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }>
                {selectedSurveyType=="PJU" && 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:16,color:'black'}}>Nama JPU</Text>
                                    <Text style={{fontSize:16,color:'black'}}>Jenis</Text>
                                    <Text style={{fontSize:16,color:'black'}}>Tanggal Installasi</Text>
                                    <Text style={{fontSize:16,color:'black'}}>Status</Text>
                                </View>
                                <View style={{ flexDirection:'column',paddingLeft:0,width:'45%'}}>
                                    <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.pju_name}</Text>
                                    <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.pju_type}</Text>
                                    <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.installation_date}</Text>
                                    <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.status}</Text>
                                </View>
                                <View style={{flexDirection:'column',width:'20%'}}>
                                    <View style={{}}>
                                        <View>
                                            <TouchableOpacity onPress={()=> {
                                                deleteById(item.pju_name);
                                                removeValue(item.id+" / "+item.pju_name+" / "+item.pju_type+" / "+item.installation_date+" / "+item.status+" / "+item.keterangan+" / "+item.long+" / "+item.lat+" / sentPJU");
                                            }}>
                                                <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                    <Image
                                                        source={require('../../assets/icon/delete.png')}
                                                        style={{width:25,height:25}}
                                                    />
                                                </View>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                    <View style={{}}>
                                        <View>
                                            <TouchableOpacity onPress={() => {
                                                navigation.navigate('Edit',{ screen: 'Edit',data: {
                                                    id:item.id,
                                                    nama:item.pju_name,
                                                    jenis:item.pju_type,
                                                    tanggal_installasi:item.installation_date,
                                                    status:item.status,
                                                    keterangan:item.keterangan,
                                                    long:item.long,
                                                    lat:item.lat
                                                }});
                                                // setLocalStorage([])
                                            }}>
                                                <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                    <Image
                                                        source={require('../../assets/icon/pen.png')}
                                                        style={{width:25,height:25}}
                                                    />
                                                    {/* <Text style={{fontSize:18,fontWeight:'bold'}}>View</Text> */}
                                                </View>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            </View>
                            <View
                                style={{
                                    marginTop: 10,
                                    marginBottom: 10,
                                    borderBottomColor: 'black',
                                    borderBottomWidth: 1,
                                }}
                            />
                        </View> 
                    ))
                :
                selectedSurveyType=="PDAM" && 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:16,color:'black'}}>Nama Pipa</Text>
                                <Text style={{fontSize:16,color:'black'}}>Jenis</Text>
                                <Text style={{fontSize:16,color:'black'}}>Tanggal Installasi</Text>
                                <Text style={{fontSize:16,color:'black'}}>Status</Text>
                            </View>
                            <View style={{ flexDirection:'column',paddingLeft:0,width:'45%'}}>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.pipe_name}</Text>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.pipe_type}</Text>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.installation_date}</Text>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.status}</Text>
                            </View>
                            <View style={{flexDirection:'column',width:'20%'}}>
                                <View style={{}}>
                                    <View>
                                        <TouchableOpacity onPress={()=> {
                                            // deleteById(item.pipe_name);
                                            // removeValue(item.id+" / "+item.pipe_name+" / "+item.pipe_type+" / "+item.installation_date+" / "+item.status+" / "+item.keterangan+" / "+item.geom+" / sentPDAM");
                                        }}>
                                            <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                <Image
                                                    source={require('../../assets/icon/delete.png')}
                                                    style={{width:25,height:25}}
                                                />
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={{}}>
                                    <View>
                                        <TouchableOpacity onPress={() => {
                                            navigation.navigate('PDAM Editing',{ screen: 'Edit',data: {
                                                id:item.id,
                                                nama:item.pipe_name,
                                                jenis:item.pipe_type,
                                                tanggal_installasi:item.installation_date,
                                                status:item.status,
                                                keterangan:item.keterangan,
                                            }});
                                            // setLocalStorage([])
                                        }}>
                                            <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                <Image
                                                    source={require('../../assets/icon/pen.png')}
                                                    style={{width:25,height:25}}
                                                />
                                                {/* <Text style={{fontSize:18,fontWeight:'bold'}}>View</Text> */}
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        </View>
                        <View
                            style={{
                                marginTop: 10,
                                marginBottom: 10,
                                borderBottomColor: 'black',
                                borderBottomWidth: 1,
                            }}
                        />
                    </View> 
                ))
                :
                selectedSurveyType=="PERMIT" && 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:16,color:'black'}}>Company Name</Text>
                                <Text style={{fontSize:16,color:'black'}}>Permit Status</Text>
                                <Text style={{fontSize:16,color:'black'}}>Location</Text>
                            </View>
                            <View style={{ flexDirection:'column',paddingLeft:0,width:'45%'}}>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.company_name}</Text>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.permit_status}</Text>
                                <Text style={{fontSize:16,fontWeight:'bold',color:'black'}}>: {item.location}</Text>
                            </View>
                            <View style={{flexDirection:'column',width:'20%'}}>
                                <View style={{}}>
                                    <View>
                                        <TouchableOpacity onPress={()=> {
                                            deleteById(item.company_name);
                                            removeValue(item.id+" / "+item.company_name+" / "+item.permit_status+" / "+item.location+" / "+item.geom+" / sentPermit");
                                        }}>
                                            <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                <Image
                                                    source={require('../../assets/icon/delete.png')}
                                                    style={{width:25,height:25}}
                                                />
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={{}}>
                                    <View>
                                        <TouchableOpacity onPress={() => {
                                            navigation.navigate('Permit Editing',{ screen: 'Edit',data: {
                                                id:item.id,
                                                company_name:item.company_name,
                                                permit_status:item.permit_status,
                                                location:item.location,
                                            }});
                                            // setLocalStorage([])
                                        }}>
                                            <View style={{flexDirection:'row',justifyContent:'flex-end',padding:6}}>
                                                <Image
                                                    source={require('../../assets/icon/pen.png')}
                                                    style={{width:25,height:25}}
                                                />
                                                {/* <Text style={{fontSize:18,fontWeight:'bold'}}>View</Text> */}
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        </View>
                        <View
                            style={{
                                marginTop: 10,
                                marginBottom: 10,
                                borderBottomColor: 'black',
                                borderBottomWidth: 1,
                            }}
                        />
                    </View> 
                ))  
                :<View style={{alignItems:'center',padding:20}}>
                <Text style={{fontSize:16,color:'grey'}}>Data Kosong</Text>
            </View>
                }
            </ScrollView>
            <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}}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ecf0f1',
        padding: 10,
      },
    mainContainer: {
        flex: 1,
        padding: 10,
    },
    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 SentListScreen;