/*
FileName:UserSupport.js
Version:1.0.0
Purpose: User Support Screen
Devloper:Mahesh Reddy
*/
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, StatusBar, Dimensions, Picker, TouchableOpacity, Linking, TextInput, Alert } from 'react-native';
import { Title, Button, Container, Content, Header, Right, Left, Body, Tab, Tabs, TabHeading, Footer, Item, Input, FooterTab } from 'native-base';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import SearchableDropdown from 'react-native-searchable-dropdown';
import AsyncStorage from '@react-native-community/async-storage';
// import { tsMethodSignature } from '@babel/types';
import { API, CHATAPI } from "../WebServices/RestClient";
import NetInfo from '@react-native-community/netinfo';
import Snackbar from 'react-native-snackbar';
import ModalSelector from 'react-native-modal-selector';
// import { Dropdown } from 'react-native-material-dropdown';
import log from '../LogFile/Log';
import Toast from 'react-native-whc-toast';
import { MAINTASKINFO, MAINTASKTITLE, DESCRIPTION, } from '../CommonComponents/Header';
import { ScrollView } from 'react-native-gesture-handler';
import { EMPLOYEEID1, FULLNAME, USERNAME1, EMAIL1, MOBILE1, ADDEMPLOYEE, EMPLOYEEDETAILS } from '../CommonComponents/Header';
import RadioButtonRN from 'radio-buttons-react-native';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';

const options = {
    title: 'Select Image',
    type: 'library',
    options: {
        maxHeight: 200,
        maxWidth: 200,
        selectionLimit: 1,
        mediaType: 'photo',
        includeBase64: false
    },
}

export default class UserSupport extends Component {

    constructor(props) {
        super(props);

        this.state = {
            email_to_contact: '',
            bug_one_sen: '',
            steps_for_bug: '',
            docFile: '',

        };
    }
    //upload Report
    reportBugimage = async () => {
        log("Info", " onSignIn( usertype, user_status, password) is used to Adding the new Employee");
        const images = await launchImageLibrary(options);

        if (this.isValid()) {



            AsyncStorage.multiGet(["cropcode", "userName", "fullName"], (err, response) => {
                const cropcode = response[0][1];
                const userName = response[1][1];
                const { empId, bug_one_sen, steps_for_bug, docFile } = this.state;
                const data = new FormData();
                data.append('file', {
                    uri: images.assets[0].uri,
                    type: images.assets[0].type,
                    name: images.assets[0].fileName,
                })
                data.append('action', 'releaseBug');
                data.append('api', CHATAPI);
                data.append('bug_one_sen', bug_one_sen);
                data.append('email_to_contact', userName);
                data.append('steps_for_bug', steps_for_bug);

                NetInfo.fetch().then(state => {
                    if (state.type == "none") {
                        console.log(state.type);
                        log("Warn", "No internet connection");
                        Snackbar.show({
                            title: 'No Internet Connection',
                            backgroundColor: 'red',
                            duration: Snackbar.LENGTH_LONG,
                        });
                    } else {
                        fetch(API + 'report_bug.php', {
                            method: 'post',
                            body: data,
                            headers: {
                                'Content-Type': 'multipart/form-data; ',
                            },
                        }).then((response) => response.json())
                            .then((responseJson) => {
                                //alert(responseJson);
                                console.log(JSON.stringify(responseJson));
                                console.log(responseJson);
                                alert("Your report was sent successfully")

                                if (responseJson.status === 'True') {

                                    this.setState({ 
                                        bug_one_sen: '',
                                        steps_for_bug:''
    
                                    });

                                    this.props.navigation.navigate('MyTask');

                                }
                                else {
                                    console.log(JSON.stringify(responseJson));
                                    log("Warn", "Error  found");
                                    // alert("error");
                                    // alert(responseJson.message)
                                }

                            }).catch((error) => {
                                console.error(error);
                                log("Error", "Adding the new Employee error");
                            });
                    }
                });
       
    });

}
    }
//upload Report
reportBug(){

    if (this.isValid()) {


        AsyncStorage.multiGet(["cropcode", "userName", "fullName"], (err, response) => {
            const cropcode = response[0][1];
            const userName = response[1][1];
            const { empId, bug_one_sen, steps_for_bug, docFile } = this.state;

            const data = new FormData();
            data.append('file', '')
            data.append('action', 'releaseBug');
            data.append('api', CHATAPI);
            data.append('bug_one_sen', bug_one_sen);
            data.append('email_to_contact', userName);
            data.append('steps_for_bug', steps_for_bug);

            NetInfo.fetch().then(state => {
                if (state.type == "none") {
                    console.log(state.type);
                    log("Warn", "No internet connection");
                    Snackbar.show({
                        title: 'No Internet Connection',
                        backgroundColor: 'red',
                        duration: Snackbar.LENGTH_LONG,
                    });
                } else {
                    fetch(API + 'report_bug.php', {
                        method: 'post',
                        body: data,
                        headers: {
                            'Content-Type': 'multipart/form-data; ',
                        },
                    }).then((response) => response.json())
                        .then((responseJson) => {
                            // alert(responseJson);
                            console.log(JSON.stringify(responseJson));
                            console.log(responseJson);
                            // alert("Your report was sent successfully")
                            

                            if (responseJson.status === 'True') {
                                alert(responseJson.message);
                                this.setState({ 
                                    bug_one_sen: '',
                                    steps_for_bug:''

                                });
                                this.props.navigation.navigate('MyTask');



                            }
                            else {
                                console.log(JSON.stringify(responseJson));
                                log("Warn", "Error  found");
                                // alert("error");
                                alert(responseJson.message)
                            }

                        }).catch((error) => {
                            console.error(error);
                            log("Error", "Adding the new Employee error");
                        });
                }
            });
        });


    }
}
//Checking the Validations start
isValid() {
    var { email_to_contact, bug_one_sen, steps_for_bug } = this.state;
    let valid = false;

    // if (empId.length === 0) {
    //     log("Warn", "empId should not be empty");
    //     alert("Enter Employee Id");
    // }

    // if (!this.verifyEmail(email_to_contact)) {
    //     log("Warn", "Email should not be empty");
    //     alert("Enter Email");
    // }
    if (bug_one_sen.length === 0) {
        log("Warn", "Bug should not be empty");
        alert("Enter Bug Report");
    }

    else if (steps_for_bug.length === 0) {
        log("Warn", "Steps should not be empty");
        alert("Enter Steps of Bugs");
    }

    // else if (mobile.length === 0) {
    //     log("Warn", "mobile should not be empty");
    //     alert("Enter phonenumber");
    // }
    // else if (mobile.length > 10) {
    //     log("Warn", "mobile should not be greater than 10");
    //     alert("Invalid phonenumber");
    // }
    // else if (mobile.length < 10) {
    //     log("Warn", "mobile should not be less than 10");
    //     alert("Invalid phonenumber");
    // }

    else {
        valid = true;
    }
    return valid;
}
verifyEmail(email_to_contact) {
    var reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return reg.test(email_to_contact);
}
//Checking the Validations end






//Add or Mpdify the Maintask close
// componentDidMount() {
//     //Getting Employees List
//     log("Debug", "Add Task screen is loaded");

// }

render() {

    return (
        <Container>
            <Header
                androidStatusBarColor="#00A2C1"
                style={{
                    backgroundColor: '#00A2C1',
                    height: 60,
                    width: Dimensions.get('window').width,
                    borderBottomColor: '#ffffff',
                    justifyContent: 'space-between',
                }}>
                <Left>
                    <Icon name="menu" size={25} style={{ color: '#fff' }} onPress={() =>
                        this.props.navigation.toggleDrawer()} />
                </Left>
                <Body>
                    <Title style={{ color: '#fff', fontWeight: '600' }}>Support</Title>
                </Body>

            </Header>


            <Content>
                <Toast ref="toast" />

                <View style={{ paddingTop: 20, }}>
                    <Text style={{ paddingTop: 10, paddingLeft: 20 }}>
                        Tell us about the bug you found!
                        </Text>
                </View>
                <View style={{ paddingTop: 20, }}>

                    <View style={{ paddingLeft: 10, }}>
                        <View style={{ width: wp('95%'), }}>
                            <Text>
                                Could You Please Describe This Bug In One Sentence?*                            </Text>
                        </View>
                        <View>

                            <TextInput style={{ width: wp('95%'), height: 45, borderBottomWidth: 1, }}
                                placeholder="Scrum board or Active Sprint: Sprint Name not displaying "
                                underlineColorAndroid='transparent'
                                // value={this.state.bug_one_sen}
                                onChangeText={(bug_one_sen) => this.setState({ bug_one_sen })}

                            />
                        </View>
                    </View>
                    <View style={{ paddingLeft: 10, }}>
                        <View style={{ width: wp('95%'), }}>
                            <Text>
                                Let Us Know How To Reproduce The Bug For Us To Work On?*
                                                           </Text>
                        </View>
                        <View>

                            <TextInput style={{ width: wp('95%'), height: 45, borderBottomWidth: 1, }}
                                placeholder="1. Go to Dashboards | 2. Add a new Project "
                                // maxLength={10}
                                // keyboardType={"number-pad"}
                                underlineColorAndroid='transparent'
                                // value={this.state.steps_for_bug}
                                onChangeText={(steps_for_bug) => this.setState({ steps_for_bug })}

                            />
                        </View>

                    </View>
                    <TouchableOpacity style={styles.upload}
                            onPress={this.reportBugimage} >
                            <Text style={{ color: 'white' }}>Uplaod</Text>
                        </TouchableOpacity>

                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: "space-between" }}>



                        <TouchableOpacity style={styles.opensave}
                            onPress={this.reportBug.bind(this)} >
                            <Text style={{ color: 'white' }}>Submit</Text>
                        </TouchableOpacity>
                    </View>

                </View>
            </Content>
        </Container>
    );
}
}
//Styles for UI
const styles = StyleSheet.create({
    opencancel: {
        flex: 1,
        ...Platform.select({
            ios: {
                backgroundColor: 'red', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
            android: {
                backgroundColor: 'red', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
        }),
    },
    opensave: {
        flex: 1,
        ...Platform.select({
            ios: {
                backgroundColor: 'green', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
            android: {
                backgroundColor: 'green', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
        }),
    },
    upload: {
        flex: 1,
        ...Platform.select({
            ios: {
                backgroundColor: 'orange', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
            android: {
                backgroundColor: 'orange', margin: 20, height: 30, alignItems:
                    "center", justifyContent: 'center'
            },
        }),
    },
});