import {
  faAngleDown,
  faArrowLeft,
  faEdit,
  faPlus,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation, useRoute } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import * as ImagePicker from "expo-image-picker";
import {
  get_barangays,
  get_cities,
  get_manila_cities,
  get_provinces,
} from "../../services/addressApi/address";
import SelectDropdown from "react-native-select-dropdown";
import {
  update_customer,
  uploadImage,
} from "../../services/api/controllers/customers";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";

const AccountAndSecurity = ({ route }) => {
  const navigation = useNavigation();
  const [unit, setunit] = useState("");
  const { isrefresh, userData } = route.params ?? "";

  const [street, setstreet] = useState("");
  const [fName, setfName] = useState(userData.first_name ?? "");
  const [lName, setlName] = useState(userData.last_name ?? "");
  const [username, setusername] = useState(userData.user_login ?? "");

  const [email, setemail] = useState(userData.user_email ?? "");
  const [phone, setphone] = useState(userData.phone_number ?? "");

  const [error, seterror] = useState("");
  const [load, setload] = useState(false);
  const toast = useToast();
  const [selectedImage, setSelectedImage] = useState(null);
  const [image, setimage] = useState(null);

  // const route = useRoute();

  // console.log("address " + address?.length);
  const [user, setuser] = useState([]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        console.log(pass);
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);

  console.log("addresss " + isrefresh);
  const UpdateUser = () => {
    console.log(userData._id);
    setload(true);
    if (image) {
      uploadImage(image)
        .then((result) => {
          console.log("Image uploaded successfully:", result.data);
          // Handle success (e.g., show success message)
          // Alert.alert('Image uploaded successfully');
          console.log(result.data.filename);
          update_customer({
            id: userData?._id ?? "",
            body: {
              first_name: fName,
              last_name: lName,
              user_login: username,
              phone_number: phone,
              customer_image: `https://api.obanana.shop/images/storage/customer_uploads/${result.data.filename}`,
            },
          })
            .then((result3) => {
              if (result3.error) {
                seterror(result3.error);
              } else {
                // setaddreses(result3.data.addreses);
                setload(false);
                toast.show("Successfully updated user!", {
                  type: "success",
                  placement: "top",
                  duration: 2000,
                  offset: 30,
                  animationType: "slide-in",
                });
                navigation.navigate("AccountSettings", {
                  isrefresh: isrefresh === true ? false : true,
                });
                console.log(result3.data);
              }
              // update_customer({
              //   id: userData?._id ?? "",
              //   body: {
              //     last_name: lName,
              //   },
              // })
              //   .then((result1) => {
              //     update_customer({
              //       id: userData?._id ?? "",
              //       body: {
              //         user_login: username,
              //       },
              //     })
              //       .then((result2) => {
              //         update_customer({
              //           id: userData?._id ?? "",
              //           body: {
              //             phone_number: phone,
              //           },
              //         })
              //           .then((result3) => {
              //             if (result3.error) {
              //               seterror(result3.error);
              //             } else {
              //               // setaddreses(result3.data.addreses);
              //               setload(false);

              //               navigation.navigate("AccountSettings", {
              //                 isrefresh: isrefresh === true ? false : true,
              //               });
              //               console.log(result3.data);
              //             }
              //           })
              //           .catch((error) => {
              //             // setError(error.message);
              //             console.log(error.message);
              //           });
              //       })
              //       .catch((error) => {
              //         // setError(error.message);
              //         console.log(error.message);
              //       });
              //   })
              //   .catch((error) => {
              //     // setError(error.message);
              //     console.log(error.message);
              //   });
            })
            .catch((error) => {
              // setError(error.message);
              console.log(error.message);
            })
            .finally(() => {
              // setprodIsLoading(false); // Set loading to false when done loading
              // console.log(result.data);
            });
        })
        .catch((error) => {
          console.error("Error uploading image:", error);

          // Handle error (e.g., show error message)
          // Alert.alert('Error uploading image');
        });
    } else {
      update_customer({
        id: userData?._id ?? "",
        body: {
          first_name: fName,
          last_name: lName,
          user_login: username,
          phone_number: phone,
          // customer_image: `https://api.obanana.shop/images/storage/vendor_uploads/${result.filename}`,
        },
      })
        .then((result3) => {
          if (result3.error) {
            seterror(result3.error);
          } else {
            // setaddreses(result3.data.addreses);
            setload(false);
            toast.show("Successfully updated user!", {
              type: "success",
              placement: "top",
              duration: 2000,
              offset: 30,
              animationType: "slide-in",
            });
            navigation.navigate("AccountSettings", {
              isrefresh: isrefresh === true ? false : true,
            });
            console.log(result3.data);
          }
          // update_customer({
          //   id: userData?._id ?? "",
          //   body: {
          //     last_name: lName,
          //   },
          // })
          //   .then((result1) => {
          //     update_customer({
          //       id: userData?._id ?? "",
          //       body: {
          //         user_login: username,
          //       },
          //     })
          //       .then((result2) => {
          //         update_customer({
          //           id: userData?._id ?? "",
          //           body: {
          //             phone_number: phone,
          //           },
          //         })
          //           .then((result3) => {
          //             if (result3.error) {
          //               seterror(result3.error);
          //             } else {
          //               // setaddreses(result3.data.addreses);
          //               setload(false);

          //               navigation.navigate("AccountSettings", {
          //                 isrefresh: isrefresh === true ? false : true,
          //               });
          //               console.log(result3.data);
          //             }
          //           })
          //           .catch((error) => {
          //             // setError(error.message);
          //             console.log(error.message);
          //           });
          //       })
          //       .catch((error) => {
          //         // setError(error.message);
          //         console.log(error.message);
          //       });
          //   })
          //   .catch((error) => {
          //     // setError(error.message);
          //     console.log(error.message);
          //   });
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
          // console.log(result.data);
        });
    }
  };

  const selectImage = async () => {
    const permissionResult =
      await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      Alert.alert("Permission to access camera roll is required!");
      return;
    }

    const pickerResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!pickerResult.canceled) {
      setSelectedImage({ localUri: pickerResult.assets[0].uri });

      // Prepare image data for upload
      const imageData = {
        image_id: userData._id,
        category: "customer",
        imageFile: {
          uri: pickerResult.assets[0].uri,
          type: "image/jpeg", // Adjust the type if needed
          name: "image.jpg", // Adjust the name if needed
        },
      };
      setimage(imageData);
      // Call your uploadImage function

      console.log(imageData);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() =>
            navigation.navigate("AccountSettings", { isrefresh: { isrefresh } })
          }
          style={styles.backIcon}
        >
          <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
        </TouchableOpacity>
        <Text style={styles.headerText}>Edit Profile</Text>
      </View>

      <ScrollView style={styles.wrapper}>
        {/* <Text style={styles.text}>Content</Text> */}
        <View style={styles.wrap}>
          <View style={styles.accountPrev}>
            <TouchableOpacity
              style={styles.accountPrevWrap}
              onPress={() => {
                selectImage();
              }}
            >
              {selectedImage ? (
                <Image
                  style={{
                    width: 100,
                    height: 100,
                    resizeMode: "cover",
                    borderRadius: 100,
                    // marginLeft: 20,
                  }}
                  source={{
                    uri: selectedImage.localUri,
                  }}
                />
              ) : (
                <Image
                  style={{
                    width: 100,
                    height: 100,
                    resizeMode: "cover",
                    borderRadius: 100,
                    // marginLeft: 20,
                  }}
                  source={{
                    uri:
                      userData.customer_image ??
                      "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyvLBxIU54Q3fueLL83PvG1eNSofzpwE-iwA&usqp=CAU",
                  }}
                />
              )}

              <View style={styles.editprof}>
                <FontAwesomeIcon icon={faEdit} size={24} color={"#333"} />
              </View>
            </TouchableOpacity>
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>First Name:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setfName(e);
              }}
              value={fName}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Last Name:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setlName(e);
              }}
              value={lName}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Username:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setusername(e);
              }}
              value={username}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>

          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Phone Number:</Text>
            {/* <View style={styles.inputNum}> */}
            {/* <Text>+63 </Text> */}
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setphone(e);
              }}
              value={phone}
              // placeholder="9*********"
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
            {/* </View> */}
          </View>
          {/* <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Email:(optional)</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setemail(e);
              }}
              value={email}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View> */}
        </View>
      </ScrollView>
      <View style={styles.footer}>
        <TouchableOpacity style={styles.footerBtn} onPress={() => UpdateUser()}>
          <Text style={styles.footerBtnText}>Save</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffff",
    width: "100%",
    height: "100%",
  },
  wrapper: {
    height: "100%",
    width: "100%",
    marginBottom: 60,
  },
  wrap: {
    height: "100%",
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 30,
  },
  header: {
    alignItems: "center",
    width: "100%",
    top: 0,
    paddingLeft: 15,
    flexDirection: "row",
    borderColor: "#ddd",
    paddingBottom: 15,
    borderBottomWidth: 1,
  },
  headerText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 25,
  },
  wrapMiddleFormInput: {
    marginVertical: 6,
  },
  input: {
    height: 50,
    width: 300,
    margin: 10,
    borderWidth: 1,
    padding: 15,
    borderColor: "#bebebe",
    borderRadius: 10,
    backgroundColor: "#fff",
  },
  inputNum: {
    height: 50,
    width: 300,
    margin: 5,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
    flexDirection: "row",
    // justifyContent: "center",9
    alignItems: "center",
    backgroundColor: "#fff",
  },
  inputText: {
    marginLeft: 15,
    fontSize: 13,
    fontWeight: "600",
  },
  footer: {
    position: "absolute",
    bottom: 0,
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 10,
  },
  footerBtn: {
    backgroundColor: "#ff5e00",
    width: "90%",
    paddingVertical: 10,
    justifyContent: "center",
    borderRadius: 20,
    alignItems: "center",
    flexDirection: "row",
  },
  footerBtnText: {
    color: "#fff",
    fontSize: 16,
    marginRight: 10,
  },
  selectBtnText: {
    color: "#929292",
    fontSize: 15,
    marginRight: 10,
    letterSpacing: 0.6,
  },
  editprof: {
    position: "absolute",
    right: 0,
    bottom: 5,
  },
  accountPrev: {
    marginBottom: 25,
  },
  accountPrevWrap: {
    borderWidth: 4,
    borderStyle: "dashed",
    borderColor: "#ffaa00c0",
    padding: 10,
    margin: 15,
  },
});

export default AccountAndSecurity;
