import * as React from 'react';
import { useState } from 'react';
import { Button, View, Text, TextInput, SectionList, Image, TouchableOpacity, Sc, PermissionsAndroid, ScrollView} from 'react-native';
import { createDrawerNavigator, DrawerContentScrollView, DrawerItemList, DrawerItem} from '@react-navigation/drawer';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { SafeAreaView } from 'react-native';
import { BottomSheet } from 'react-native-btr';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Ionics from 'react-native-vector-icons/Ionicons';
import { MaterialDatetimePickerAndroid } from 'react-native-material-datetime-picker';
import { DateTimePickerAndroid } from '@react-native-community/datetimepicker';
import { NavigationAction } from '@react-navigation/native';
import RNMaterialDatetimePicker from 'react-native-material-datetime-picker';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import ImagePicker from 'react-native-image-crop-picker';
import SidebarScreen from '../sidebar';
import styles from './style';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
import RBSheet from 'react-native-raw-bottom-sheet';


const logo = require ('../../images/pic.png');
const cutlery = require ('../../images/cutlery.png');
const card = require ('../../images/credit-card.png');
const salary = require ('../../images/salary.png');
const motor = require('../../images/car.png');
const wallet = require ('../../images/wallet.png');
const cash = require ('../../images/money.png');
const cart = require ('../../images/shoppingcart.png');
const health = require ('../../images/firstaidkit.png');
const sale = require ('../../images/sale.png');
const awards = require ('../../images/medal.png');
const less = require ('../../images/less.png');
const greater = require('../../images/greater.png');
const calendar = require('../../images/calendar.png');
const plus = require ('../../images/plus.png');
const acc = require ('../../images/acc.png');
const tag = require ('../../images/tag.png');
const clear = require ('../../images/clear.png');
const drop = require ('../../images/drop.png');
const goalcolor = require('../../images/roundedrectangle.png');
const caricon = require ('../../images/caricon.png');
const Stack = createNativeStackNavigator();
const profile = require ('../../images/user.png');

const Profile =()=> {

  const [fname, onChangeFName] = useState('Farhani');
  const [lname, onChangeLName] = useState('Halim');
  const [email, onChangeEmail] = useState('farhanihalim@gmail.com');
  const [password, onChangePassword] = useState('');
  const [confirmPassword, onChangeConfirmPassword] = useState('');
  const [dob, setDOB] = useState('06/02/1999');
  const [gender, setGender] = useState('Female');

  const [profilePic, setProfilePic] = useState(profile);
  const [isUploadOptionVisible, setUploadOptionVisible] = useState(false);

  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisibility(false);
  };

  const handleConfirm = (date) => {
    console.warn("A date has been picked: ", date);
    hideDatePicker();
  };


  // launchCamera(options, callback);
  // const result = async launchCamera(options);

  // launchImageLibrary(options, callback);
  // const resultt = await launchImageLibrary(options);
 
  const [filePath, setFilePath] = useState({});
 
  const requestCameraPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: 'Camera Permission',
            message: 'App needs camera permission',
          },
        );
        // If CAMERA Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        return false;
      }
    } else return true;
  };
 
  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 captureImage = async (type) => {
    let options = {
      mediaType: 'photo',
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
      videoQuality: 'low',
      durationLimit: 30, //Video max duration in seconds
      saveToPhotos: true,
    };
    let isCameraPermitted = await requestCameraPermission();
    let isStoragePermitted = await requestExternalWritePermission();
    if (isCameraPermitted && isStoragePermitted) {
      launchCamera(options, (response) => {
        console.log('Response = ', response);
 
        if (response.didCancel) {
          // alert('User cancelled camera picker');
          return;
        } else if (response.errorCode == 'camera_unavailable') {
          alert('Camera not available on device');
          return;
        } else if (response.errorCode == 'permission') {
          alert('Permission not satisfied');
          return;
        } else if (response.errorCode == 'others') {
          alert(response.errorMessage);
          return;
        }
        console.log('base64 -> ', response.base64);
        console.log('uri -> ', response.uri);
        console.log('width -> ', response.width);
        console.log('height -> ', response.height);
        console.log('fileSize -> ', response.fileSize);
        console.log('type -> ', response.type);
        console.log('fileName -> ', response.fileName);
        setFilePath(response);
      });
    }
  };
 
  const chooseFile = (type) => {
    let options = {
      mediaType: 'photo',
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
      selectionLimit: 1,
      includeBase64:true
    };
    launchImageLibrary(options, (response) => {
      console.log('Response = ', response);
 
      if (response.didCancel) {
        // alert('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        alert('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        alert('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        alert(response.errorMessage);
        return;
      }
      console.log('base64 -> ', response.base64);
      console.log('uri -> ', response.uri);
      console.log('width -> ', response.width);
      console.log('height -> ', response.height);
      console.log('fileSize -> ', response.fileSize);
      console.log('type -> ', response.type);
      console.log('fileName -> ', response.fileName);
      setFilePath(response);
    });
  };

    return (
        <SafeAreaView style={{flex:1}}>
        <View style = {{backgroundColor:'white', height:'100%'}}>
          <ScrollView>
            <View style={{marginHorizontal:20, marginTop:20}}>
              <Text style={{marginBottom:20, fontSize:15,marginHorizontal:5}}>Profile photo</Text>
                <View style = {{flexDirection:'row'}}>
                 <View style ={{flexDirection:'row', marginHorizontal:25}}>
                   <View style={{backgroundColor:'#2693ff', elevation:8, justifyContent:'center', alignItems:'center', borderRadius:25, width:50, height:50}}>
                    <Image style={{width: 60, height: 60,  borderColor:'powderblue', borderWidth: 1, elevation: 7,borderRadius: 100,}} source={profilePic}/>
                   </View>
                 </View>

                 
                    <View style={{flexDirection:'row'}}>
                      <TouchableOpacity style={styles.saveButton} onPress={()=>{this.RCSheet.open()}}>
                      <RBSheet
                       ref={ref => {
                       this.RCSheet = ref;
                        }}
                       height={300}
                       openDuration={250}
                       closeOnDragDown={true}
                       customStyles={{
                       container: {
                       justifyContent: "flex-start",
                       height:170,
                       }
                      }}
                      >
              <View>
                 <Text style={{color:'black', fontSize:18, fontWeight:'500', marginHorizontal:20}}>Profile Photo</Text>
                    <View style={{flexDirection:'row', marginTop:25}}>
                      <View>
                        <TouchableOpacity
                          activeOpacity={0.5}
                          onPress={() => captureImage('photo')}>
                          <View style={{
                            height:50, 
                            width:50, 
                            borderRadius:100, 
                            borderColor:'lightgrey', 
                            borderWidth:0.5, 
                            marginHorizontal:25
                            }}
                            >
                              <Ionics 
                               name="camera" 
                               size={30} 
                               color="grey" 
                               style={{
                               marginHorizontal:9, 
                               marginVertical:7
                              }}
                             />
                          </View>
                              <Text style={{
                               color:'grey', 
                               marginHorizontal:27, 
                               marginTop:5
                               }}
                               >
                               Camera
                              </Text>
                        </TouchableOpacity>
                      </View>

                      <View>
                       <TouchableOpacity
                        activeOpacity={0.5}
                        onPress={() => chooseFile('photo')}>
                         <View style={{
                          height:50, 
                          width:50, 
                          borderRadius:100, 
                          borderColor:'lightgrey', 
                          borderWidth:0.5, 
                          marginHorizontal:25
                          }}
                          >
                            <Ionics name="image" 
                                    size={30} 
                                    color="grey" 
                                    style={{
                                    marginHorizontal:10, 
                                    marginVertical:7
                                  }}
                                  /> 
                        </View>
                         <Text style={{
                          color:'grey', 
                          marginHorizontal:29, 
                          marginTop:5}}>
                            Gallery
                            </Text>
                        </TouchableOpacity>
                      </View>
                    </View>
                  </View>
                </RBSheet>
                        <View style={{flexDirection:'row'}}>
                           <Icon name="upload" size={20} color="#5eb5ce"/>
                              <Text style={{color:'#5eb5ce', marginHorizontal:10, fontSize:15}}>Upload Picture</Text>
                        </View>
                     </TouchableOpacity>

                     <TouchableOpacity style={styles.button}>
                        <Icon name="delete" size={20} color="red"/>
                     </TouchableOpacity>
                  </View>
                    
                </View>
                         <View style={{marginTop:30, flexDirection:'row', justifyContent:'space-between', width:'100%'}}>
                            <Text style={{fontSize:15, marginHorizontal:5}}>First Name</Text>
                            <Text style={{fontSize:15, marginHorizontal:90}}>Last Name</Text>
                        </View>
                        <View style={{marginTop:10, marginHorizontal:5,flexDirection:'row', justifyContent:'space-between', width:'100%'}}>
                            <View style={styles.input}> 
                            <TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} onChangeFName={onChangeFName} value={fname} fontSize={15}/></View>
                            <View style={[styles.input,{marginRight:10}]}>
                            <TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} onChangeFName={onChangeLName} value={lname} fontSize={15}/>
                            </View>
                        </View>

                        <View style={{marginTop:30, flexDirection:'column',}}>
                            <Text style={{fontSize:15, marginHorizontal:5}}>Email</Text>
                            <View style={{marginTop:10, flexDirection:'row',}}>
                            <View style={[styles.input,{width:350}]}><TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} onChangeEmail={onChangeEmail} value={email} fontSize={15}/></View>
                        </View>
                        </View>

                        <View style={{marginTop:30, flexDirection:'column',}}>
                            <Text style={{fontSize:15, marginHorizontal:5}}>Password</Text>
                            <View style={{marginTop:10, flexDirection:'row',}}>
                            <View style={[styles.input,{width:350}]}><TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} onChangePassword={onChangePassword} value={password} fontSize={15}/></View>
                        </View>
                        </View>

                        <View style={{marginTop:30, flexDirection:'column',}}>
                            <Text style={{fontSize:15, marginHorizontal:5}}>Confirm Password</Text>
                            <View style={{marginTop:10, flexDirection:'row',}}>
                            <View style={[styles.input,{width:350}]}><TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} onChangeConfirmPassword={onChangeConfirmPassword} value={confirmPassword} fontSize={15}/></View>
                        </View>
                        </View>

                        <View style={{marginTop:30, flexDirection:'row', justifyContent:'space-between', width:'100%'}}>
                            <Text style={{fontSize:15, marginHorizontal:5}}>DOB</Text>
                            <Text style={{fontSize:15, marginHorizontal:110}}>Gender</Text>
                        </View>

                        <View style={{marginTop:10, marginHorizontal:5,flexDirection:'row', justifyContent:'space-between', width:'100%'}}>
                            <View style={[styles.input,{flexDirection:'row', justifyContent:'space-between'}]}> 
                            <View style={{flexDirection:'row', width:'60%'}}>
                               <TextInput style={{marginTop:3, fontSize:15,}} setDOB={setDOB} value={dob} fontSize={15}/>
                               </View>
                                  <View style={{flexDirection:'row', width:'20%', marginTop:8}}>
                                      <Ionics name="calendar-outline" size={20} color="grey"/>
                                  </View>
                            </View>
                            <View style={[styles.input,{marginRight:10}]}>
                            <TextInput style={{marginTop:3, fontSize:15, marginHorizontal:2}} setGender={setGender} value={gender} fontSize={15}/>
                            </View>
                        </View>
                        

                        <View style={{flexDirection:'row'}}>
                          <TouchableOpacity style={{alignItems: "center",
                                                    backgroundColor: "dodgerblue",
                                                    padding: 10,
                                                    width:'40%',
                                                    borderRadius:5,
                                                    marginTop:40,
                                                    marginHorizontal:100}}>
                        <Text style={{color:'white', fontWeight:'bold'}}>Save Changes</Text>
                     </TouchableOpacity>
                  </View>

                        </View>

                    </ScrollView>
</View>
</SafeAreaView>
    );
};

export default Profile;