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 {launchCamera, launchImageLibrary} from 'react-native-image-picker';
import InputSpinner from 'react-native-input-spinner';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import ItemScreen from '../ItemScreen';
import AddItemScreen from '../AddItemScreen';
const plusbutton = require('../../images/plusbutton.png');
// const editbutton = require('../../images/editbutton.png');
// const deletebutton = require ('../../images/deletebutton.png');
var db = openDatabase({ name: 'shoppinglist.db'});

const ListScreen = ({navigation}) => {
  const [addImageVisible, setAddImageVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [manageListModalVisible, setManageListModalVisible] = useState(false);
  const [confirmEditModalVisible, setConfirmEditModalVisible] = useState(false);
  const [id, setId] = useState ('');
  const [name, setName] = useState('');
  const [quantity, setQuantity] = useState(0);
  const [image, setImage] = useState('');
  const [updateItem, setUpdateItem] = useState ([]); 
  const [items, setItems] = useState ([]);
  const [emptyList, setEmptyList] = useState ([]);
  const [selectedId, setSelectedId] = useState ('');
  const [imageUri, setImageUri]= useState('');
  
  // create table
  useEffect(() => {
    db.transaction(function (txn) {
        txn.executeSql(
            "SELECT name from sqlite_master WHERE type='table' AND name='list'",
            [],
            function (tx, res) {
                console.log('item:', res.rows.length);
                if (res.rows.length == 0) {
                    txn.executeSql('DROP TABLE IF EXISTS list', []);
                    txn.executeSql(
                        'CREATE TABLE IF NOT EXISTS list(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(100), quantity INT(10), image LONGTEXT)',
                        [],
                    );
                }
            },
        );
    });
}, []);

// add into list
const insertList = () => {
  console.log(name, quantity, imageUri);
  if (name == '') {
    alert('Please enter name');
    // return;
   } 
  // else if (quantity == 0){
  //   alert('Please enter quantity');
  // }
  // else if (imageUri == ''){
  //   alert('Please insert photo');
  // }
  else{
    setAddModalVisible(false)
db.transaction(function (tx) {
  tx.executeSql(
    'INSERT INTO list (name, quantity, image) VALUES (?,?,?)',
    [name, quantity, imageUri],
    (tx, results) => {
      console.log('Data insert :', results.rowsAffected);
      if (results.rowsAffected > 0) {
        Alert.alert(
          'Success!',
          'Data inserted successfully',
          );
        onRefresh()
        setName(''), setQuantity(0), setImageUri('')
      } else alert('Add list failed');
    },(error)=>{
      console.log(JSON.stringify(error))
    }
  );
});
  }
}

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

// update list
const updateList = () => {
  console.log(selectedId, name, quantity, image);
  console.log(updateItem.name, updateItem.quantity, updateItem.image);
  var n = ''
  var q = 0
  var i = ''
  if (name == '' && updateItem.name == ''){
    alert('Please enter name');
  } 
  else if (quantity == 0 && updateItem.quantity == 0){
    alert('Please enter quantity');
  } 
  else if (image == '' && updateItem.image == ''){
    alert('')
  }
  else {
    if(name == ''){
      n = updateItem.name
    }
    else{
      n = name
    }
    if(quantity == 0){
      q = updateItem.quantity
    }
    else{
      q = quantity
    }
    if(image == ''){
      i = updateItem.image
    }
    else{
      i = image
    }
    console.log(n,q,i)
    setEditModalVisible(false)
    setManageListModalVisible(false)
  db.transaction((tx) => {
    tx.executeSql(
      'UPDATE list set name = ?, quantity = ?, image = ? where id = ?',
      [n, 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('ListScreen'),
              },
            ],
            { cancelable: false }
          );
          onRefresh()
          setName(''), setQuantity(0), setImage('')
        } (error)=>{
          console.log(JSON.stringify(error))
        }
      }
    );
  });
 }
};

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

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

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

const emptyMessage = (status) => {
  return(
    <View 
      style={{ 
        justifyContent: 'center', 
        alignItems: 'center', 
        flex: 1 , 
        marginLeft:10, 
        marginRight:10,
        flexDirection:'column'
        }}>
           <Text 
             style={{ 
              fontSize: 20, 
              textAlign: 'center',
              fontFamily:'Poppins-SemiBold',
              color:'gray'
              }}>
                  Let's plan your shopping!
           </Text>
           <Text 
             style={{ 
              fontSize: 20, 
              textAlign: 'center',
              fontFamily:'Poppins-Light',
              color:'gray',
              marginTop:10
              }}>
                  Tap + button to create your first list
           </Text>
    </View>
);
}

const requestCameraPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        title: "Cool Photo App Camera Permission",
        message:
          "Cool Photo App needs access to your camera " +
          "so you can take awesome pictures.",
        buttonNeutral: "Ask Me Later",
        buttonNegative: "Cancel",
        buttonPositive: "OK"
      }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera");
    } else {
      console.log("Camera permission denied");
    }
  } catch (err) {
    console.warn(err);
  }
};

const requestExternalWritePermission = async () => {
  if (Platform.OS === 'android') {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'External Storage Write Permission',
          message: 'App needs write permission',
        },
      );
      // If WRITE_EXTERNAL_STORAGE Permission is granted
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn(err);
      alert('Write permission err', err);
    }
    return false;
  } else return true;
};

const openCamera = () => {
  requestCameraPermission()
  const options={
    storageOption : {
      path:'images',
      mediaType:'photo',
    },
    includeBase64: true,
  };

  launchCamera(options, response => {
    console.log('Response = ', response);
    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
      alert(response.customButton);
    } else {
      console.log('Response else = ', response);
      const source = response.assets[0].uri
      console.log(source)
      setImage(source);
      setImageUri(source);
      setAddImageVisible(false);
    }
  });
};

const openGallery = () => {
  requestExternalWritePermission()
  const options={
    storageOption : {
      path:'images',
      mediaType:'photo',
    },
    includeBase64: true,
  };

  launchImageLibrary(options, response => {
    console.log('Response = ', response);
    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
      alert(response.customButton);
    } else {
      const source = response.assets[0].uri
      console.log(source)
      setImage(source);
      setImageUri(source);
      setAddImageVisible(false);
    }
  });
};


const listItemView = ( item ) => (
  <View 
    style = {
      styles.outerContainer
    }>
      <View 
        style = {
          styles.listCard
        }>
          <View 
           style={{
             flexDirection:'row'
           }}>
              <View 
                style = {styles.imageContainer}>
                  {/* <Image 
                    style = {[styles.imageSize,{}]} 
                    source={{uri : item.image}}
                  /> */}
                    <View 
                      style={{
                        flexDirection:'row', 
                        marginHorizontal:10, 
                        width:'200%'
                      }}>
                         <Text 
                            style={[
                              styles.textName,
                              {marginTop:1}
                            ]}>
                              {item.name}
                        </Text>
                                <View 
                                  style={{
                                    flexDirection:'row'
                                  }}>
                                </View>
                                        {/* <Text 
                                          style={[
                                            styles.textName,
                                            {}
                                          ]}>
                                             Quantity: {item.quantity}
                                        </Text> */}
                    </View>
                    <TouchableOpacity style={{marginHorizontal:150, width:'50%'}} onPress={()=>setManageListModalVisible(true)}>
                                   <MaterialIcons 
                                      name="more-vert"
                                      color="grey"
                                      size={30}
                                   />
                                   </TouchableOpacity>
                            <View>
                            {/* <Text>Test : {item.quantity}</Text> */}
                            </View>
                            {/* <TouchableOpacity 
                              style={[
                                styles.editDeleteContainer,
                                {}
                              ]} 
                                onPress = {()=>{setEditModalVisible(true), setUpdateItem(item), setSelectedId(item.id), setImage(item.image)}}
                              >
                                <MaterialCommunityIcons 
                                  name="square-edit-outline" 
                                  size={30} 
                                  color='white'
                                />
                            </TouchableOpacity>
                                               <TouchableOpacity 
                                                 style={[
                                                  styles.editDeleteContainer,
                                                  {marginHorizontal:10,}
                                                  ]} 
                                                  onPress = {()=>{setDeleteModalVisible(true), setSelectedId(item.id)}}
                                                  >
                                                    <MaterialCommunityIcons 
                                                      name="delete" 
                                                      size={30} 
                                                      color='white'
                                                    />
                                               </TouchableOpacity> */}
                                              
               </View>
          </View>
      </View>
  </View>
  )

  const AddImage = () => {
    if(addImageVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={addImageVisible}
          onRequestClose={() =>{
            Alert.alert("Modal has been closed.");
            setAddImageVisible(!addImageVisible);
          }}>
             <View 
               style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(192,192,192,0.8)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>
                  <TouchableOpacity 
                   style={{
                    height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                   }} 
                    onPress = {()=>{setAddImageVisible(false)}}>
                  </TouchableOpacity>
                             <View 
                                style={styles.centeredView}>
                                  <View 
                                    style={styles.centeredView}>
                                     <View 
                                       style={styles.addImageView}>
                                            <TouchableOpacity
                                              style={{
                                                justifyContent:'flex-start'
                                              }}
                                                onPress={()=>setAddImageVisible(false)}
                                              >
                                                 <MaterialCommunityIcons
                                                   name="close-circle" 
                                                   size={30} 
                                                   color='white'
                                                 />
                                            </TouchableOpacity>
                                                               <View 
                                                                style={{
                                                                  alignItems:'center',
                                                                  marginTop:1
                                                                }}>
                                                                   <Text 
                                                                     style={{
                                                                      fontSize:20, 
                                                                      color:'black', 
                                                                      fontWeight:'bold',
                                                                      justifyContent:'center'
                                                                    }}>
                                                                       Add image
                                                                   </Text>
                                                                          <TouchableOpacity 
                                                                            onPress={() => {openCamera()}}
                                                                           >
                                                                            <View 
                                                                              style={{
                                                                                marginTop:25
                                                                              }}>
                                                                                 <Text 
                                                                                   style={{
                                                                                     fontSize:15, 
                                                                                     color:'black',
                                                                                   }}>
                                                                                     Take photo
                                                                                 </Text>
                                                                            </View>
                                                                          </TouchableOpacity>
                                                                                            <TouchableOpacity 
                                                                                              onPress={() => openGallery()}
                                                                                              >
                                                                                              <View 
                                                                                                 style={{
                                                                                                  marginTop:15
                                                                                                }}>
                                                                                                  <Text
                                                                                                    style={{
                                                                                                      fontSize:15, 
                                                                                                      color:'black'
                                                                                                    }}>
                                                                                                       Add from gallery
                                                                                                  </Text>
                                                                                              </View>
                                                                                            </TouchableOpacity>
                                                              </View>

                                      </View>
                                  </View>
                              </View>
              </View>
        </Modal>
        
      )
    }
}

  const ManageListModal = () => {
    if(manageListModalVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={manageListModalVisible}
          onRequestClose={()=> {
            // Alert.alert("Modal has been closed.");
            setManageListModalVisible(!manageListModalVisible);
          }}>
            <View 
              style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(192,192,192,0.8)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>
                <TouchableOpacity
                  style={{
                    height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                  }}
                  onPress={() => setManageListModalVisible(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
                     }}>
                       Photo
                   </Text>
                         <TouchableOpacity
                           style={{
                            marginHorizontal:40,
                            flexDirection:'row',
                            marginTop:20,
                           }}
                             onPress={()=> setEditModalVisible(true)}
                           >
                             <MaterialCommunityIcons
                               name="camera"
                               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 AddListModal = () => {
    // console.log("Results "+ imageUri)
    // var img = imageUri != null && imageUri != undefined && imageUri != ''  ? {uri:imageUri} : ''
    if(addModalVisible){
      return(
        <Modal
          animationType="none"
          transparent={true}
          visible={addModalVisible}
          onRequestClose={() => {
            Alert.alert("Modal has been closed.");
            setAddModalVisible(!addModalVisible);
          }}>
            <View 
               style={{
                height:'100%', 
                width:'100%', 
                backgroundColor:'rgba(192,192,192,0.8)', 
                justifyContent:'center', 
                alignItems:'center'
              }}>

                <TouchableOpacity 
                   style={{
                     height:'100%', 
                     width:'100%', 
                     position:'absolute', 
                     top:0, 
                     flex:1
                   }}  
                     onPress={() => setAddModalVisible(false)}
                />
                  <View style={styles.addModalView}>
                    <View 
                      style={{
                        alignItems:'center',
                        marginTop:35,
                      }}>
                        <Text 
                          style={{
                            fontSize:20, 
                            color:'black', 
                            fontFamily:'Poppins-Regular'
                          }}>
                              Create new list
                        </Text>
                    </View>

                           <View 
                              style={{
                                flexDirection:'row', 
                                marginTop:20
                              }}>
                                <View 
                                  style={{
                                    backgroundColor:'#ededed', 
                                    borderRadius:9, 
                                    width:275, 
                                    height:50, 
                                    marginHorizontal:19,
                                    marginTop:10,
                                    // elevation:8,
                                    // borderWidth:0.2,
                                    // borderColor:'white',
                                    justifyContent:'center',
                                    alignContent:'flex-start',
                                    alignItems:'flex-start',
                                    alignSelf:'center',
                                  }}>
                                      <TextInput 
                                        style={{
                                          fontSize:20,
                                          marginHorizontal:5, 
                                          fontFamily:'Poppins-SemiBold',
                                          alignItems:'center',
                                          width:'100%',
                                          // textAlignVertical:'top',
                                        }}
                                          placeholder="New List"
                                          placeholderTextColor="grey"
                                          onChangeText={(name) => setName(name)}
                                              
                                      />
                                </View>
                           </View>
                                  <View 
                                     style={{
                                       flexDirection:'row', 
                                       margin:25, 
                                       marginTop:45,
                                       justifyContent:'space-between',
                                       marginBottom:40
                                     }}>
                                        <TouchableOpacity 
                                          style={{
                                            marginHorizontal:5
                                          }} 
                                            onPress={() => setAddModalVisible(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'
                                                    }}>
                                                        CANCEL
                                                  </Text>
                                            </View>
                                        </TouchableOpacity>
                                                           <TouchableOpacity 
                                                              style={{
                                                                marginHorizontal:5
                                                              }}
                                                                 onPress={() => navigation.navigate('ItemScreen')}
                                                                // onPress={insertList}
                                                              > 
                                                                <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'
                                                                        }}>
                                                                            CREATE
                                                                     </Text>
                                                                </View>
                                                            </TouchableOpacity>
                                  </View>
                  </View>  
            </View>
        </Modal>
    )
  }
}

const EditListModal = () => {
  // console.log("Results  " + image)
  if(editModalVisible){
    return(
      <Modal
      animationType="none"
      transparent={true}
      visible={editModalVisible}
      onRequestClose={() => {
        // Alert.alert("Modal has been closed.");
        setEditModalVisible(!editModalVisible);
      }}>
        <View 
           style={{
            height:'100%', 
            width:'100%', 
            backgroundColor:'rgba(192,192,192,0.8)', 
            justifyContent:'center', 
            alignItems:'center'
          }}>

            <TouchableOpacity 
               style={{
                 height:'100%', 
                 width:'100%', 
                 position:'absolute', 
                 top:0, 
                 flex:1
               }}  
                 onPress={() => setEditModalVisible(false)}
            />
              <View style={styles.addModalView}>
                <View 
                  style={{
                    alignItems:'center',
                    marginTop:35,
                  }}>
                    <Text 
                      style={{
                        fontSize:20, 
                        color:'black', 
                        fontFamily:'Poppins-Regular'
                      }}>
                          Rename list
                    </Text>
                </View>

                       <View 
                          style={{
                            flexDirection:'row', 
                            marginTop:20
                          }}>
                            <View 
                              style={{
                                backgroundColor:'#ededed', 
                                borderRadius:9, 
                                width:275, 
                                height:50, 
                                marginHorizontal:19,
                                marginTop:10,
                                justifyContent:'center',
                                alignContent:'flex-start',
                                alignItems:'flex-start',
                                alignSelf:'center',
                              }}>
                                  <TextInput 
                                    style={{
                                      fontSize:20,
                                      marginHorizontal:5, 
                                      fontFamily:'Poppins-SemiBold',
                                      alignItems:'center',
                                      textAlignVertical:'top',
                                      width:'100%'
                                    }}
                                      placeholder="Rename List"
                                      placeholderTextColor="grey"
                                      onChangeText={(name) => setName(name)}
                                          
                                  />
                            </View>
                       </View>
                              <View 
                                 style={{
                                   flexDirection:'row', 
                                   margin:25, 
                                   marginTop:45,
                                   justifyContent:'space-between',
                                   marginBottom:40,
                                 }}>
                                    <TouchableOpacity 
                                      style={{
                                        marginHorizontal:5
                                      }} 
                                        onPress={() => {setConfirmEditModalVisible(true)}}
                                      >
                                        <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'
                                                }}>
                                                    CANCEL
                                              </Text>
                                        </View>
                                    </TouchableOpacity>
                                                       <TouchableOpacity 
                                                          style={{
                                                            marginHorizontal:5
                                                          }}
                                                            // onPress={() => navigation.navigate('ItemScreen')}
                                                            // onPress={updateList}
                                                          > 
                                                            <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'
                                                                    }}>
                                                                        SAVE
                                                                 </Text>
                                                            </View>
                                                        </TouchableOpacity>
                              </View>
              </View>  
        </View>
    </Modal>
  )
 }
}

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(192,192,192,0.8)', 
              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),setManageListModalVisible(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={deleteList}
                                                                     >
                                                                       <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 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(192,192,192,0.8)', 
              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), setEditModalVisible(false), setManageListModalVisible(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>
    )
  } 

}
    return (
    <SafeAreaView 
      style={{
        flex:1, 
        width:'100%'
      }}>
          <View 
            style={{
              flex:1, 
              backgroundColor:'white', 
              width:'100%'
            }}>
               {emptyList ? emptyMessage(emptyList): 
                 <FlatList
                  data={items}
                  ItemSeparatorComponent={listViewItemSeparator}
                  keyExtractor={(item,index) => index.toString()}
                  renderItem={({item}) => listItemView(item)}
                 />
               } 
                 <TouchableOpacity 
                   style={{ 
                    // backgroundColor:'red', 
                    elevation:7, 
                    justifyContent:'center', 
                    alignItems:'center', 
                    alignContent:'center',
                    position:'absolute', 
                    borderRadius:100,  
                    right:24, 
                    bottom:20
                  }} 
                    onPress={() => 
                     setAddModalVisible(true)
                    }>
                       <View 
                         style={{
                          backgroundColor: '#0077eb',
                          width:130,
                          height: 50,
                          flexDirection:'row',
                          justifyContent:'center',
                          alignContent:'center',
                          alignItems:'center',
                          borderRadius:100
                         }}>
                            <MaterialCommunityIcons
                              name="plus"
                              size={25} 
                              color='white'
                            />
                              <Text 
                                style={{
                                  fontFamily:'Poppins-Regular', 
                                  fontSize:18, 
                                  color:'white', 
                                  alignSelf:'center',
                                  marginTop:5,
                                  marginHorizontal:5
                                }}>  
                                   NEW LIST
                              </Text>
                         </View>
                 </TouchableOpacity>  
          </View> 
           {AddImage()}
           {AddListModal()}  
           {EditListModal()}
           {DeleteListModal()}
           {confirmEditModal()}
           {ManageListModal()}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
    topContainer:{
      width:'100%',
      height:80,
      backgroundColor:'white',
    },
    outerContainer:{
      width:'100%',
      flex:1,
      backgroundColor:'white'
    },
    listCard:{
      width:'95%',
      height:100,
      backgroundColor:'white',
      marginTop:10,
      marginBottom:5,
      marginHorizontal:10,
      borderRadius:8,
      elevation:5,
      // borderWidth:2,
       borderColor:'white',
    },
    headerTitle:{
      fontSize:29,
      justifyContent:'center',
      alignItems:'center',
      marginHorizontal:100,
      marginTop:30,
      color:'pink',
    },
    imageSize:{
      width:75,
      height:75,
      justifyContent:'center',
      alignItems:'center',
      borderWidth:0.1,
      borderColor:'#ffdae0',
      borderRadius:5,

    },
    imageContainer:{
      //  borderWidth:5,
      flexDirection:'row',
      // backgroundColor:'red',
      marginTop:11,
      marginHorizontal:8,
      height:80,
      width:80,
  
    },
    textName:{
      // flexDirection:'row',
      // marginHorizontal:10,
       width:'200%',
      // marginTop:10,
      fontSize:20,
      fontFamily: 'Poppins-SemiBold',
      color:'black'
    
    },
    // textQuantity:{
    //   flexDirection:'row',
    //   marginHorizontal:10,
    //   marginBottom:10,
    //   // width:'75%',
    //   // marginTop:15,
    //   fontSize:15,
    // },
    editDeleteContainer:{
      width:40,
      height:40,
      backgroundColor:'#ffa7b5',
      marginTop:20,
      // marginHorizontal:10,
      borderRadius:8,
      borderColor:'pink',
      elevation:8,
      justifyContent:'center', 
      alignItems:'center',
      alignContent:'center'
    },
    addButton:{
      width:60, 
      height:60,
    },
    centeredView:{
      flex:1,
      justifyContent: "center",
      alignItems: "center",
      marginTop: 22,
      // backgroundColor:'white',
    },
    addModalView:{
      position:'absolute',
      marginHorizontal:100,
      backgroundColor:'white',
      borderRadius:20,
      // padding:25,
      width:'80%',
      height:300,
      // justifyContent:'center',
      // alignItems:'center',
      shadowOffset:{
        width:0,
        height:2
      },
      shadowOpacity:0.25,
      shadowRadius:4,
      elevation:5
    },
    editModalView:{
      position:'absolute',
      marginHorizontal:100,
      backgroundColor:'pink',
      borderRadius:20,
      padding:25,
      width:'80%',
      height:450,
      // justifyContent:'center',
      // alignItems:'center',
      shadowOffset:{
        width:0,
        height:2
      },
      shadowOpacity:0.25,
      shadowRadius:4,
      elevation: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
    },
    addImageView:{
      position:'absolute',
      marginHorizontal:100,
      backgroundColor:'pink',
      borderRadius:20,
      padding:10,
      width:'80%',
      height:200,
      // justifyContent:'center',
      // alignItems:'center',
      shadowColor:'#000',
      shadowOffset:{
        width:0,
        height:2
      },
      shadowOpacity:0.25,
      shadowRadius:4,
      elevation:5
    },
    manageModalView:{
      position:'absolute',
      // marginHorizontal:100,
      backgroundColor:'white',
      borderRadius:7,
      // padding:25,
      width:'42%',
      height:'13%',
      justifyContent:'flex-start',
      // flex:1,
      // marginTop:'auto',
      // justifyContent:'center',
      // alignItems:'center',
      shadowOffset:{
        width:0,
        height:2
      },
      shadowOpacity:0.25,
      shadowRadius:4,
      elevation:5
    },
  });

export default ListScreen;