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 Ionicons from 'react-native-vector-icons/Ionicons';
import ListScreen from '../ListScreen';
import ItemScreen from '../ItemScreen';
const plusbutton = require('../../images/plusbutton.png');
var db = openDatabase({ name: 'shoppinglist.db'});
// const editbutton = require('../../images/editbutton.png');
// const deletebutton = require ('../../images/deletebutton.png');

const AddItemScreen = ({navigation}) => {
  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 [addImageModalVisible, setAddImageModalVisible] = useState(false);
  const AddImageModal = () => {
  if(addImageModalVisible){
    return(
      <Modal
        animationType="none"
        transparent={true}
        visible={addImageModalVisible}
        onRequestClose={() =>{
        setAddImageModalVisible(!addImageModalVisible);
        }}
        >
          <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={() => setAddImageModalVisible(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,
                           }}>
                             <Ionicons
                               name="camera"
                               size={30}
                               color="#838383"
                             />
                              <Text 
                                style={{
                                  alignSelf:'center', 
                                  textAlignVertical:'center', 
                                  marginHorizontal:30, 
                                  fontFamily:'Poppins-Regular', 
                                  fontSize:20, 
                                  color:'black', 
                                  marginTop:5
                                }}>
                                   Take a photo
                              </Text> 
                         </TouchableOpacity>
                         <TouchableOpacity
                           style={{
                            marginHorizontal:40,
                            flexDirection:'row',
                            marginTop:20,
                           }}>
                             <Ionicons
                               name="md-images"
                               size={30}
                               color="#838383"
                             />
                              <Text 
                                style={{
                                  alignSelf:'center', 
                                  textAlignVertical:'center', 
                                  marginHorizontal:30, 
                                  fontFamily:'Poppins-Regular', 
                                  fontSize:20, 
                                  color:'black', 
                                  marginTop:5
                                }}>
                                   Pick from gallery
                              </Text> 
                         </TouchableOpacity>
               </View>      
          </View>
      </Modal>
    )
  }
}
  
    return(
      <View
        style={
          styles.container
        }>
          <TouchableOpacity
            style={
              styles.cameraContainer
            }
             onPress={() => setAddImageModalVisible(true)}
            >
              <Ionicons
                name="camera"
                size={30}
                color="#838383"
              />
          </TouchableOpacity>
                            <View
                              style={
                                styles.imageContainer
                              }>
                            </View>
                            
                                  <View
                                    style={
                                      styles.itemContainer
                                    }>
                                      <TextInput
                                        style={
                                          styles.textItem
                                        }
                                        placeholder="Butter"
                                        //placeholderTextColor="grey"
                                        >
                                      </TextInput>
                                  </View>
                                        <View
                                          style={
                                            styles.quantityContainer
                                          }>
                                            <View 
                                              style={{
                                                justifyContent:'center', 
                                                alignContent:'center', 
                                                alignItems:'center', 
                                                alignSelf:'center'
                                              }}>
                                                <InputSpinner
                                                  // value={quantity} 
                                                  min={0}
                                                  max={100}
                                                  step={1}
                                                  // onChange={(quantity) => setQuantity(quantity)}
                                                  onLimitReached={(isMax, msg) => console.log(isMax,msg)}
                                                  rounded
                                                  // showBorder skin='default'
                                                  textColor='black'
                                                  fontSize={20}
                                                  fontFamily="Poppins-Regular"
                                                  colorMin='white' 
                                                  colorMax='white' 
                                                  buttonTextColor='dodgerblue'
                                                  colorPress="dodgerblue"
                                                  color='white'
                                                  width={320}
                                                  height={50}
                                                />
                                            </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',
                                                        marginTop:50,
                                                      }}>
                                                        <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',
                                                                          marginTop:50,
                                                                        }}>
                                                                          <Text 
                                                                            style={{
                                                                              fontSize:20, 
                                                                              color:'white',
                                                                              fontFamily:'Poppins-Medium'
                                                                            }}>
                                                                               SAVE
                                                                          </Text>
                                                                      </View>
                                                                    </TouchableOpacity>
                              </View>
                              {AddImageModal()}
                                                 
      </View>
    );
};

const styles = StyleSheet.create({
    container:{
      backgroundColor:'white',
      flex:1,
    },
    cameraContainer:{
      left:350,
      marginTop:30,
    },
    imageContainer:{
      width:200,
      height:200,
      backgroundColor:'white',
      justifyContent:'center',
      alignContent:'center',
      alignItems:'center',
      alignSelf:'center',
      borderRadius:9,
      elevation:7,
      marginTop:20,
    },
    itemContainer:{
      width:360,
      height:60,
      backgroundColor:'#ededed',
      justifyContent:'center',
      alignContent:'flex-start',
      alignItems:'flex-start',
      alignSelf:'center',
      borderRadius:9,
      // elevation:7,
      marginTop:50,
    },
    textItem:{
      fontFamily:'Poppins-Regular',
      fontSize:20,
      color:'black',
      marginHorizontal:20,
      width:'100%',
      marginTop:5,
    },
    quantityContainer:{
      width:360,
      height:60,
      backgroundColor:'#ededed',
      justifyContent:'center',
      alignContent:'center',
      alignItems:'flex-start',
      alignSelf:'flex-start',
      borderRadius:9,
      // elevation:7,
      marginTop:30,
      marginHorizontal:16,
    },
});
export default AddItemScreen;