import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  Button,
  TextInput,
  View,
  Text,
  TouchableOpacity,
  ImageBackground,
} from "react-native";
import { Entypo } from "@expo/vector-icons";
import axios from "axios";
import { State } from "react-native-gesture-handler";
import * as SecureStore from 'expo-secure-store'




export function SignIn({ navigation }) {

  const [data, setData] = useState({
    email: "",
    password: "",
    isValidUser: true,
    isValidPassword: true,
    check_textinputChange: false,
  });

  const textInputChange = (val) => {
    if (val.trim().length >= 4 && val.includes('@')) {
      setData({
        ...data,
        email: val,
        check_textInputChange: true,
        isValidUser: true,
      });
    } else {
      setData({
        ...data,
        email: val,
        check_textInputChange: false,
        isValidUser: false,
      });
    }
  };

  const handlePasswordChange = (val) => {
    if (val.trim().length >= 4) {
      setData({
        ...data,
        password: val,
        isValidPassword: true,
      });
    } else {
      setData({
        ...data,
        password: val,
        isValidPassword: false,
      });
    }
  };


  const form = new FormData ();

  form.append("email", data.email)
  form.append("password", data.password)

  console.log(form)

  return (
    <View style={styles.container}>
      <ImageBackground
        source={require("../assets/signin1.jpg")}
        style={styles.images}
      >
        <View style={styles.secondContainer}>
          <View style={styles.SectionStyle}>
            <Text style={styles.text}>HELLO</Text>
            <Text style={styles.text1}>Sign In to your Account</Text>

            <View style={styles.textinputicon}>
              <Entypo name="user" size={30} color="white" />
              <TextInput
                style={styles.input1}
                onChangeText={(val) => textInputChange(val)}
                placeholder="Enter Email" //dummy@abc.com
                placeholderTextColor="#8b9cb5"
                keyboardType="email-address"
                // onBlur={() => emailValidator()}
                // onSubmitEditing={() =>
                //     passwordInputRef.current &&
                //     passwordInputRef.current.focus()
                // }
                blurOnSubmit={false}
              />
            </View>
            {data.isValidUser ? null : (
              <Text style={styles.errorMsg}>
                Email must be 4 characters long and iclude @
              </Text>
            )}
          </View>

          <View style={styles.SectionStyle}>
            <View style={styles.textinputicon}>
              <Entypo name="lock" size={30} color="white" />
              <TextInput
                style={styles.input1}
                onChangeText={(val) => handlePasswordChange(val)}
                placeholder="Enter Password" //12345
                placeholderTextColor="#8b9cb5"
                // ref={passwordInputRef}
                // onSubmitEditing={Keyboard.dismiss}
                blurOnSubmit={false}
                secureTextEntry={true}
              />
            </View>
            {data.isValidPassword ? null : (
              <Text style={styles.errorMsg}>
                Password must be minimum 4 characters long.
              </Text>
            )}
          </View>
          <View style={styles.buttons}>
            <TouchableOpacity
              style={styles.buttonSub}
              activeOpacity={0.5}
              onPress={  () =>  navigation.navigate("HomeScreen") }
                // axios.post("http://192.168.8.126:5000/login", form)
                //   .then( async function (response) {
                //     // const stngobj = JSON.stringify()
                //     console.log(response.data);
                //     // alert("Successfully Logged in");
                //     await SecureStore.setItemAsync("token", response.data.token);

                //     axios.defaults.headers.common = {
                //       authorization : response.data.token
                //     }

                //     navigation.navigate("HomeScreen")

                //     // return response;
                //   })
                //   .catch(function (error) {
                //     console.log(error);
                //     alert("No User Existed")
                //   })
            >
              <Text style={styles.buttonTextStyle}>LOGIN</Text>
              {/* <ImageBackground source={require('../assets/loginex.jpg')} style={styles.imagebutton}/> */}
            </TouchableOpacity>

            <View
              style={{
                flexDirection: "row",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <Text style={{ color: "black", textAlign: "center" }}>
                Dont have an account
              </Text>
              <TouchableOpacity
                style={styles.buttonSignUp}
                title="Sign Up"
                onPress={() => navigation.navigate("SignUp")}
              >
                <Text style={styles.buttonText}>Sign Up</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  input: {
    borderWidth: 1,
    borderColor: "#ddd",
    padding: 10,
    paddingTop: 10,
    fontSize: 15,
    borderRadius: 25,
    marginTop: 20,
    marginBottom: 10,
    marginLeft: 19,
    marginRight: 19,
    backgroundColor: "white",
  },
  buttonSub: {
    width: "83%",
    padding: 10,
    marginTop: 30,
    marginLeft: 30,
    marginHorizontal: 10,
    backgroundColor: "#ff426e",
    flexDirection: "row",
    marginBottom: 20,
    justifyContent: "center",
    borderRadius: 8,
  },
  images: {
    height: "100%",
    justifyContent: "center",
  },

  text: {
    fontSize: 30,
    alignSelf: "center",
    marginTop: 5,
    color: "black",
  },
  text1: {
    fontSize: 15,
    alignSelf: "center",
    marginBottom: 20,
    color: "black",
  },
  container: {
    justifyContent: "flex-start",
    alignContent: "stretch",
  },
  secondContainer: {
    justifyContent: "flex-start",
  },
  textinputicon: {
    // flex: 1,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    // backgroundColor: '#fff',
    color: "yellow",
  },
  input1: {
    borderWidth: 1,
    borderColor: "#ddd",
    padding: 10,
    // paddingTop: 10,
    fontSize: 15,
    borderRadius: 25,
    marginTop: 20,
    marginBottom: 10,
    marginLeft: 10,
    marginRight: 19,
    backgroundColor: "white",
    width: "75%",
  },
  buttonSignUp: {
    width: "20%",
    // padding: 10,
    marginLeft: 10,
    // marginHorizontal: 10,
    backgroundColor: "#ff426e",
    flexDirection: "row",
    // marginBottom: 10,
    justifyContent: "center",
    alignItems:"center",
    borderRadius: 8,
    height:35
  },
  errorMsg: {
    color: "black",
    fontSize: 14,
    alignSelf: "center",
  },
});
