import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, SafeAreaView, StyleSheet, Image, FlatList, Modal, Alert, TextInput, PermissionsAndroid, Platform, button} from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';
import InputSpinner from 'react-native-input-spinner';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import AntDesign from 'react-native-vector-icons/AntDesign';
const tick = require('../../images/tick.png');
const oil = require('../../images/oil.png');
const cat = require('../../images/cat.jpg');
const write = require('../../images/write.png');
var db = openDatabase({ name: 'shoppinglist.db'});

const ItemScreen = ({navigation}) => {
  const [addItemVisible, setAddItemVisible] = useState(false);
  const [manageItemModalVisible, setManageItemModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [confirmEditModalVisible, setConfirmEditModalVisible] = useState(false);
  const [items, setItems] = useState([]);
  const [emptyList, setEmptyList] = useState([]);
  const [updateProduct, setUpdateProduct] = useState ([]); 
  const [product, setProduct] = useState('');
  const [pic, setPic] = useState('');
  const [quantity, setQuantity] = useState('');
  const [selectedId, setSelectedId] = useState ('');
  const [text, setText] = useState ([]);
  // const [onSubmit, setOnSubmit] = useState ('');

  useEffect(() => {
  db.transaction(function (txn) {
      txn.executeSql(
          "SELECT name from sqlite_master WHERE type='table' AND name='item'",
          [],
          function (tx, res) {
              console.log('item: ', res.rows.length);
              if (res.rows.length == 0) {
                  txn.executeSql('DROP TABLE IF EXISTS item', []);
                  txn.executeSql(
                      'CREATE TABLE IF NOT EXISTS item(prodid INTEGER PRIMARY KEY AUTOINCREMENT, product VARCHAR(100), quantity INT(10), image LONGTEXT)',
                       [],
                  );
              }
          },
      );
  });
}, []);

// add into list
const insertItem = () => {
  console.log(product, quantity, pic);
  if (product == '') {
    alert('Please enter item');
   } 
  else{
    // setAddModalVisible(false)
db.transaction(function (tx) {
  tx.executeSql(
    'INSERT INTO item (product, quantity, image) VALUES (?,?,?)',
    [product, quantity, pic],
    (tx, results) => {
      console.log('Data insert : ', results.rowsAffected);
      if (results.rowsAffected > 0) {
        Alert.alert(
          'Success!',
          'Data inserted successfully.',
          [
            {
              text: 'Ok',
              onPress: () => navigation.navigate('ItemScreen'),
            },
          ],
          { cancelable: false }
        );
        onRefresh()
        setProduct(''), setQuantity(''), setPic('')
      } else alert('Add list failed');
    },(error)=>{
      console.log(JSON.stringify(error))
    }
  );
});
  }
}

// view list
useEffect(() => {
 onRefresh()
}, []);

// update list
const updateItem = () => {
  console.log(selectedId, product, quantity, pic);
  console.log(updateProduct.product, updateProduct.quantity, updateProduct.pic);
  var p = ''
  var q = ''
  var i = ''
  if (product == '' && updateProduct.product == ''){
    alert('Please enter item');
  } 
  // else if (quantity == 0 && updateItem.quantity == 0){
  //   alert('Please enter quantity');
  // } 
  // else if (image == '' && updateItem.image == ''){
  //   alert('')
  // }
  else {
    if(product == ''){
      p = updateProduct.product
    }
    else{
      p = product
    }

    console.log(p,q,i)
    // setEditModalVisible(false)
    // setManageListModalVisible(false)
  db.transaction((tx) => {
    tx.executeSql(
      'UPDATE item set product = ?, quantity = ?, image = ? where prodid = ?',
      [p, q, i, selectedId],
      (tx, results) => {
        console.log('Data update: ', JSON.stringify(results));
        if (results.rowsAffected > 0) {
          Alert.alert(
            'Success!',
            'Data updated successfully.',
            [
              {
                text: 'Ok',
                onPress: () => navigation.navigate('ItemScreen'),
              },
            ],
            { cancelable: false }
          );
          onRefresh()
          setProduct(''), setQuantity(''), setPic('')
        } (error)=>{
          console.log(JSON.stringify(error))
        }
      }
    );
  });
 }
};

//delete list
const deleteItem = () => {
  console.log('Delete item : ' + selectedId)
  var temps = selectedId
  // setDeleteModalVisible(false)
  // setManageListModalVisible(false)
  db.transaction((tx) => {
    tx.executeSql(
      'DELETE FROM item where prodid = ?',
      [temps],
      (tx, results) => {
        console.log('Data deleted ', JSON.stringify(results));
        if (results.rowsAffected > 0) {
          Alert.alert(
            'Success',
            'List deleted successfully.',
            [
              {
                text: 'Ok',
                onPress: () => navigation.navigate('ItemScreen'),
              },
            ],
            { cancelable: false }
          );
          onRefresh()
          setProduct('')
        }
      },(error)=>{
        console.log(JSON.stringify(error))
      }
    );
  });
}

const onRefresh = () => {
  db.transaction((tx) => {
    tx.executeSql(
    'SELECT * FROM item',
    [],
    (tx, results) => {
      var temps = [];
      for (let i = 0; i < results.rows.length; ++i)
      temps.push(results.rows.item(i));
      setItems(temps);
      if (results.rows.length >=1){
        setEmptyList(false);
      }else{
        setEmptyList(true)
      }
        console.log('Item: '+ JSON.stringify(temps))
      },(error)=>{
        console.log(JSON.stringify(error))
      }
    );
  });
};

  const emptyMessage = (status) => {
    return(
      <View 
        style={{ 
          justifyContent: 'center', 
          alignItems: 'center', 
          alignSelf:'center',
          alignContent:'center',
          flex: 1 , 
          marginLeft:10, 
          marginRight:10,
          flexDirection:'column'
          }}>
            <Image 
              style={{
                width:150, 
                height:150
              }} 
                source={write}
            />
             <Text 
               style={{ 
                fontSize: 20, 
                textAlign: 'center',
                fontFamily:'Poppins-SemiBold',
                color:'gray'
                }}>
                    What do you need to buy?
             </Text>
             <Text 
               style={{ 
                fontSize: 20, 
                textAlign: 'center',
                fontFamily:'Poppins-Light',
                color:'gray',
                marginTop:10
                }}>
                    Tap grey box to add your first item.
             </Text>
      </View>
  );
  }
  
  const DeleteListModal = () => {
    if(deleteModalVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={deleteModalVisible}
          onRequestClose={() => {
            Alert.alert("Modal has been closed.");
            setDeleteModalVisible(!deleteModalVisible);
        }}>
           <View 
              style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(0,0,0,.5)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>
                  <TouchableOpacity 
                    style={{
                     height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                    }}  
                      onPress={() => setDeleteModalVisible(false)}
                  />
                      <View 
                        style={
                          styles.centeredView
                        }>
                          <View 
                           style={
                            styles.deleteModalView
                           }>
                              <Text 
                                style={{
                                  fontSize:20, 
                                  color:'black', 
                                  fontFamily:'Poppins-SemiBold',
                                  marginBottom:20,
                                }}>
                                   Delete this shopping list?   
                              </Text>
                                     <Text 
                                       style={{
                                        fontSize:18, 
                                        color:'black', 
                                        fontFamily:'Poppins-Regular'
                                        }}>
                                           Are you sure?
                                      </Text>
                                              <View 
                                               style={{
                                                flexDirection:'row', 
                                                margin:20,
                                                justifyContent:'flex-start',
                                               }}>
                                                  <TouchableOpacity 
                                                    style={{
                                                      marginHorizontal:5}} 
                                                      onPress={() => {setDeleteModalVisible(false),setManageItemModalVisible(false)}}
                                                    >
                                                      <View 
                                                        style={{
                                                          backgroundColor:'#c60000', 
                                                          borderRadius:7, 
                                                          width:100, 
                                                          height:50, 
                                                          alignItems:'center', 
                                                          alignContent:'center', 
                                                          justifyContent:'center',
                                                        }}>
                                                            <Text 
                                                              style={{
                                                                fontSize:20, 
                                                                color:'white', 
                                                                alignItems:'center', 
                                                                alignContent:'center', 
                                                                justifyContent:'center',
                                                                fontFamily:'Poppins-Medium'
                                                              }}>
                                                                 NO
                                                            </Text>
                                                      </View>
                                                  </TouchableOpacity>
                                                                     <TouchableOpacity 
                                                                       style={{
                                                                        marginHorizontal:5}} 
                                                                        onPress={deleteItem}
                                                                       >
                                                                         <View 
                                                                           style={{
                                                                            backgroundColor:'#0077eb', 
                                                                            borderRadius:7, 
                                                                            width:100, 
                                                                            height:50, 
                                                                            alignItems:'center', 
                                                                            alignContent:'center', 
                                                                            justifyContent:'center'}} 
                                                                          >
                                                                            <Text 
                                                                              style={{
                                                                                fontSize:20, 
                                                                                color:'white',
                                                                                fontFamily:'Poppins-Medium'
                                                                                }}>
                                                                                   YES
                                                                            </Text>
                                                                         </View>
                                                                      </TouchableOpacity>
                                              </View>
                          </View>
                      </View> 
           </View>
        </Modal>
    )
   }
  }

  const ManageItemModal = () => {
    if(manageItemModalVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={manageItemModalVisible}
          onRequestClose={()=> {
            // Alert.alert("Modal has been closed.");
            setManageItemModalVisible(!manageItemModalVisible);
          }}>
            <View 
              style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(0,0,0,.5)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>
                <TouchableOpacity
                  style={{
                    height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                  }}
                  onPress={() => setManageItemModalVisible(false)}
                />
                 <View 
                  style={{backgroundColor:'white',
                  width:"100%",
                  height:200,
                  justifyContent:'flex-start',
                  position:'absolute',
                  bottom:0,
                  borderRadius:15,}}>
                    <Text 
                     style={{
                      fontFamily:'Poppins-SemiBold', 
                      fontSize:20, 
                      color:'black', 
                      alignSelf:'center', 
                      marginTop:20
                     }}>
                       Manage item
                   </Text>
                         <TouchableOpacity
                           style={{
                            marginHorizontal:40,
                            flexDirection:'row',
                            marginTop:20,
                           }}
                           onPress={() => navigation.navigate('AddItemScreen')}
                           >
                             <MaterialCommunityIcons
                               name="pencil"
                               size={30}
                               color="#838383"
                             />
                              <Text 
                                style={{
                                  alignSelf:'center', 
                                  textAlignVertical:'center', 
                                  marginHorizontal:30, 
                                  fontFamily:'Poppins-Regular', 
                                  fontSize:20, 
                                  color:'black', 
                                  marginTop:5
                                }}>
                                   Rename
                              </Text> 
                         </TouchableOpacity>
                         <TouchableOpacity
                           style={{
                            marginHorizontal:40,
                            flexDirection:'row',
                            marginTop:20,
                           }}
                             onPress={()=>setDeleteModalVisible(true)}
                            >
                             <MaterialCommunityIcons
                               name="delete"
                               size={30}
                               color="#c60000"
                             />
                              <Text 
                                style={{
                                  alignSelf:'center', 
                                  textAlignVertical:'center', 
                                  marginHorizontal:30, 
                                  fontFamily:'Poppins-Regular', 
                                  fontSize:20, 
                                  color:'#c60000', 
                                  marginTop:5
                                }}>
                                   Delete
                              </Text> 
                         </TouchableOpacity>
                 </View>
            </View>
        </Modal>
      )
    }
  }

  const confirmEditModal = () => {
    if(confirmEditModalVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={confirmEditModalVisible}
          onRequestClose={() => {
            // Alert.alert("Modal has been closed.");
            setConfirmEditModalVisible(!confirmEditModalVisible);
        }}>
           <View 
              style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(0,0,0,.5)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>
                  <TouchableOpacity 
                    style={{
                     height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                    }}  
                      onPress={() => setConfirmEditModalVisible(false)}
                  />
                      <View 
                        style={
                          styles.centeredView
                        }>
                          <View 
                           style={
                            styles.deleteModalView
                           }>
                              <Text 
                                style={{
                                  fontSize:20, 
                                  color:'black', 
                                  fontFamily:'Poppins-SemiBold', 
                                  marginBottom:20
                                }}>
                                   Cancel this list update?
                              </Text>
                                     <Text 
                                       style={{
                                        fontSize:18, 
                                        color:'black', 
                                        fontFamily:'Poppins-Regular'
                                        }}>
                                           Are you sure?
                                      </Text>
                                              <View 
                                               style={{
                                                flexDirection:'row', 
                                                margin:20,
                                               }}>
                                                  <TouchableOpacity 
                                                    style={{
                                                      marginHorizontal:5}} 
                                                      onPress={() => setConfirmEditModalVisible(false)}
                                                    >
                                                      <View 
                                                        style={{
                                                          backgroundColor:'#c60000', 
                                                          borderRadius:7, 
                                                          width:100, 
                                                          height:50, 
                                                          alignItems:'center', 
                                                          alignContent:'center', 
                                                          justifyContent:'center'
                                                        }}>
                                                            <Text 
                                                              style={{
                                                                fontSize:20, 
                                                                color:'white', 
                                                                alignItems:'center', 
                                                                alignContent:'center', 
                                                                justifyContent:'center',
                                                                fontFamily:'Poppins-Medium'
                                                              }}>
                                                                 NO
                                                            </Text>
                                                      </View>
                                                  </TouchableOpacity>
                                                                     <TouchableOpacity 
                                                                       style={{
                                                                        marginHorizontal:5}} 
                                                                         onPress={()=>{setConfirmEditModalVisible(false), setManageListModalVisible(false), setEditModalVisible(false)}}
                                                                       >
                                                                         <View 
                                                                           style={{
                                                                            backgroundColor:'#0077eb', 
                                                                            borderRadius:7,  
                                                                            width:100, 
                                                                            height:50, 
                                                                            alignItems:'center', 
                                                                            alignContent:'center', 
                                                                            justifyContent:'center'}} 
                                                                          >
                                                                            <Text 
                                                                              style={{
                                                                                fontSize:20, 
                                                                                color:'white',
                                                                                }}>
                                                                                   YES
                                                                            </Text>
                                                                         </View>
                                                                      </TouchableOpacity>
                                              </View>
                          </View>
                      </View> 
           </View>
        </Modal>
      )
    } 
  }

  const listItemSeparator = () =>{
    return (
      <View style={{
        // height: 0.1,
        // width: '100%',
        // backgroundColor: 'white'
      }}/>
    );
  };

  const ItemView = (item) => (
    <View
          style={
            styles.container
          }>
            <View
              style={
                styles.itemCard
              }>
               <TouchableOpacity
                 style={
                   styles.checkContainer
                 }>
                  {/* <Ionicons 
                    name="checkmark"
                    color="dodgerblue"
                    size={20}
                  /> */}
               </TouchableOpacity>
                                 <Text
                                   style={[
                                    styles.textList,
                                    {color:'black',
                                     width:'55%'
                                    }
                                   ]}>
                                     {item.product} 
                                 </Text>
                                       <Text
                                         style={[
                                          styles.textList,
                                          {color:'black',
                                           width:'7%',
                                          }
                                         ]}>
                                            {item.quantity}
                                       </Text>
                                             <TouchableOpacity
                                               style={
                                                styles.imageCointainer
                                               }>
                                                <Image 
                                                  style={{
                                                    width:50, 
                                                    height:50, 
                                                    borderRadius:100
                                                  }} 
                                                    source={cat}
                                                />
                                             </TouchableOpacity>
                                                               <TouchableOpacity
                                                                 style={{
                                                                   justifyContent:'center',
                                                                   alignItems:'center',
                                                                   alignContent:'center',
                                                                   right:2,
                                                                  }}
                                                                  onPress={() => setManageItemModalVisible(true)}>
                                                                    <MaterialIcons 
                                                                      name="more-vert"
                                                                      color="grey"
                                                                      size={30}
                                                                    />
                                                               </TouchableOpacity>
            </View>
        </View>
  )
  // const handleSubmit = event => {
  //   console.log('handleSubmit ran');
  //   event.preventDefault(); // 👈️ prevent page refresh

  //   // 👇️ clear all input values in the form
  //   setProduct('');
  // };

  // const submitClear = () => {
  //   setText([product])
  //   setProduct(' ')
  // }
    return(
      <SafeAreaView
      style={{
        flex:1,
        width:'100%'
      }}>
        <View
          style={{
            flex:1,
            backgroundColor:"white",
          }}>
            {emptyList ? emptyMessage(emptyList):
              <FlatList
               data={items}
               ItemSeparatorComponent={listItemSeparator}
               keyExtractor={(item, index) => index.toString()}
               renderItem={({item}) => ItemView(item)}
              />
            }
              <View  style={{
                                backgroundColor:'#ededed', 
                                flexDirection:'row',
                                width:'100%', 
                                height:60, 
                              }}> 
                                 <TextInput 
                                    style={{
                                      fontSize:20,
                                      marginHorizontal:10, 
                                      fontFamily:'Poppins-SemiBold',
                                      width:'100%',
                                    }}
                                      placeholder="Add new item"
                                      placeholderTextColor="grey"
                                      onChangeText={(product) => setProduct(product)}  
                                      returnKeyType="done"
                                      onSubmitEditing={insertItem}   
                                         
                                />
                                  <TouchableOpacity 
                                    style={{
                                     right:60,
                                     top:15
                                    }}
                                      // onPress={()=>{setProduct(product)}}
                                      onPress={insertItem}
                                    >
                                      <AntDesign 
                                        name="pluscircle" 
                                        color='grey' 
                                        size={30}
                                      />
                                  </TouchableOpacity>
        </View>
        </View>
        {ManageItemModal()}
        {confirmEditModal()}
        {DeleteListModal()}
    </SafeAreaView>
);
};

const styles = StyleSheet.create({
    container:{
      backgroundColor:'white',
      flex:1,
    },
    centeredView:{
      flex:1,
      justifyContent: "center",
      alignItems: "center",
      marginTop: 22,
    },
    itemCard:{
      backgroundColor:'white',
      width:'100%',
      height:70,
      elevation:7,
      marginTop:5,
      flexDirection:'row',
    },
    textList:{
      fontFamily:'Poppins-SemiBold',
      fontSize:15,
      textAlignVertical:'center',
    },
    checkContainer:{
      backgroundColor:'white',
      borderRadius:100,
      borderWidth:2,
      borderColor:'dodgerblue',
      height:25,
      width:25,
      justifyContent:'center',
      alignItems:'center',
      alignContent:'center',
      marginHorizontal:15,
      marginTop:22,
    },
    imageCointainer:{
      width:60,
      height:60,
      borderRadius:100,
      borderColor:'white',
      borderWidth:0.1,
      justifyContent:'center',
      alignItems:'center',
      alignContent:'center',
      marginTop:5,
    },
    deleteModalView:{
      position:'absolute',
      marginHorizontal:100,
      backgroundColor:'white',
      borderRadius:20,
      padding:25,
      width:'80%',
      height:200,
      // justifyContent:'center',
      alignItems:'center',
      shadowColor:'#000',
      shadowOffset:{
        width:0,
        height:2
      },
      shadowOpacity:0.25,
      shadowRadius:4,
      elevation:5
    },
});
export default ItemScreen;