import {
  faArrowRight,
  faCamera,
  faEdit,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Linking,
  TextInput,
  ActivityIndicator,
} from "react-native";
import {
  get_order,
  update_order,
} from "../../../services/api/controllers/order";
import { get_product } from "../../../services/api/controllers/product";
import * as ImagePicker from "expo-image-picker";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { uploadImage } from "../../../services/api/controllers/customers";
import { useToast } from "react-native-toast-notifications";

const ReturnForm = ({ cart, setisRefund }) => {
  const [selectedImages, setselectedImages] = useState([]);
  const [images, setImages] = useState([]);
  const [reason, setreason] = useState("");
  const [user, setuser] = useState([]);
  const [count, setcount] = useState(1);
  const [success, setsuccess] = useState(null);
  const [error, seterror] = useState(null);
  const [loading, setloading] = useState(false);
  const [isAllField, setisAllField] = useState(null);
  const [token, settoken] = useState("");

  const toast = useToast();

  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          settoken(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        console.log(pass);
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);

  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],
      allowsMultipleSelection: true,
      quality: 1,
      multiple: true, // Enable multiple selection
    });

    if (!pickerResult.canceled) {
      // Prepare image data for upload
      const imageDataArray = pickerResult.assets.map((asset) => ({
        image_id: user[0]._id + "_" + count,
        category: "order",
        imageFile: {
          uri: asset.uri,
          type: "image/jpeg", // Adjust the type if needed
          name: "image.jpg", // Adjust the name if needed
        },
      }));
      setcount(count + 1);
      setselectedImages((prevImages) => [...prevImages, ...imageDataArray]);
      // setImages(imageDataArray);

      // Call your uploadImages function passing imageDataArray
      // console.log(imageDataArray);
    }
  };
  console.log(selectedImages);

  const navigation = useNavigation();
  const getProd = (idP) => {
    console.log(idP);
    get_product({
      id: idP,
    })
      .then((result) => {
        //  console.log("result" + result);
        if (result.error) {
          // setError(result.error);
        } else if (result.data.product_type === "variation") {
          get_product({
            id: result.data.parent_id,
          })
            .then((result1) => {
              //  console.log("result" + result);

              if (result1.error) {
                // setError(result1.error);
              } else {
                // setcart(result.data);
                navigation.navigate("Product", { product: result1.data });
                console.log(result1.data);
              }
            })
            .catch((error) => {
              // setError(error.message);
            })
            .finally(() => {
              // set
            });
        } else {
          //  else {
          // setcart(result.data);
          navigation.navigate("Product", { product: result.data });
          console.log(result.data);
          // }
        }
      })
      .catch((error) => {
        // setError(error.message);
        console.log("mm " + idP);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };
  const ReturnSubmit = async () => {
    // try {
    //   // Use Promise.all to wait for all uploads to complete
    //   await Promise.all(
    //     selectedImages.map(async (imageData) => {
    //       const { category, imageFile, image_id } = imageData;
    //       try {
    //         // Call the uploadImage function for each image
    //         const result = await uploadImage(imageData)
    //           .then((result1) => {
    //             //  console.log("result" + result);

    //             if (result1.error) {
    //               // setError(result1.error);
    //             } else {
    //               // setcart(result.data);
    //               setImages([result1.data.filename, ...images]);
    //               console.log(result1.data);
    //             }
    //           })
    //           .catch((error) => {
    //             // setError(error.message);
    //           });
    //         console.log(
    //           `Image uploaded successfully for category ${category} and image ID ${image_id}`,
    //           result
    //         );
    //       } catch (uploadError) {
    //         console.error(
    //           `Error uploading image for category ${category} and image ID ${image_id}:`,
    //           uploadError
    //         );
    //         // Handle individual upload error (e.g., show an error message)
    //         // Alert.alert('Error uploading image');
    //       }
    //     })
    //   );

    //   // All uploads completed successfully
    // } catch (error) {
    //   console.error("Error uploading images:", error);
    //   // Handle general error (e.g., show an error message)
    //   // Alert.alert('Error uploading images');
    // }

    // for (const imageData of selectedImages) {
    //   const { category, imageFile, image_id } = imageData;

    //   try {
    //     const result = await uploadImage(imageData)
    //       .then((result1) => {
    //         //  console.log("result" + result);

    //         if (result1.error) {
    //           // setError(result1.error);
    //         } else {
    //           // setcart(result.data);
    //           setImages((prevImages) => [...prevImages, result1?.data?.filename]);
    //           console.log(result1.data);
    //         }
    //       })
    //       .catch((error) => {
    //         // setError(error.message);
    //       });
    //     console.log(
    //       `Image uploaded successfully for category ${category} and image ID ${image_id}`,
    //       result
    //     );
    //   } catch (uploadError) {
    //     console.error(
    //       `Error uploading image for category ${category} and image ID ${image_id}:`,
    //       uploadError
    //     );
    //     // Handle individual upload error (e.g., show an error message)
    //     // Alert.alert('Error uploading image');
    //   }
    // }

    // update_order({
    //   id: cart._id,
    //   body: {},
    // })
    //   .then((result1) => {
    //     //  console.log("result" + result);

    //     if (result1.error) {
    //       // setError(result1.error);
    //     } else {
    //       // setcart(result.data);
    //       navigation.navigate("Product", { product: result1.data });
    //       console.log(result1.data);
    //     }
    //   })
    //   .catch((error) => {
    //     // setError(error.message);
    //   })
    //   .finally(() => {
    //     // set
    //   });
    if (reason !== "" && selectedImages.length > 0) {
      setloading(true);
      let allUploadsSuccessful = true; // Variable to track the overall upload status
      var images1 = "";
      for (const imageData of selectedImages) {
        const { category, imageFile, image_id } = imageData;

        try {
          const result1 = await uploadImage(imageData);

          if (result1.error) {
            // Handle individual upload error
            console.error(
              `Error uploading image for category ${category} and image ID ${image_id}:`,
              result1.error
            );
            allUploadsSuccessful = false; // Set the status to false if any upload fails
          } else {
            // Image uploaded successfully
            setImages((prevImages) => [...prevImages, result1?.data?.filename]);
            images1 =
              images1 !== ""
                ? images1 +
                  ", " +
                  "https://api.obanana.shop/images/storage/order_uploads/" +
                  result1?.data?.filename
                : "https://api.obanana.shop/images/storage/order_uploads/" +
                  result1?.data?.filename;
            console.log(
              `Image uploaded successfully for category ${category} and image ID ${image_id}`,
              result1.data
            );
          }
        } catch (uploadError) {
          // Handle individual upload error
          console.error(
            `Error uploading image for category ${category} and image ID ${image_id}:`,
            uploadError
          );
          allUploadsSuccessful = false; // Set the status to false if any upload throws an exception
        }
      }

      if (allUploadsSuccessful) {
        // All uploads completed successfully
        console.log("All images uploaded successfully");
        console.log(images1);
        update_order({
          token: token,
          id: cart._id,
          body: {
            return_order: {
              status: "To Approve",
              reason: reason,
              image: images1,
            },
          },
        })
          .then((result1) => {
            //  console.log("result" + result);

            if (result1.error) {
              // setError(result1.error);
            } else {
              // setcart(result.data);
              // navigation.navigate("Product", { product: result1.data });
              console.log(result1.data);
              setsuccess(true);
              toast.show("Successfully sent your refund request!", {
                type: "success",
                placement: "top",
                duration: 2000,
                offset: 30,
                animationType: "slide-in",
              });
            }
            setloading(false);
          })
          .catch((error) => {
            // setError(error.message);
          })
          .finally(() => {
            // set
          });
      } else {
        // Handle the case where at least one upload failed
        setsuccess(false);

        console.error("Some images failed to upload");
      }
      setisRefund(true);
    } else {
      toast.show("Please fill in all fields!", {
        type: "danger",
        placement: "top",
        duration: 2000,
        offset: 30,
        animationType: "slide-in",
      });
    }
  };
  console.log(images);

  return (
    <View style={styles.container}>
      <Text style={styles.text4}>RETURN FORM</Text>

      <View View style={styles.wrapper}>
        <View
          style={styles.prodwrapper}
          // onPress={() => getProd(cart?.items[0]?.product?.product_id)}
        >
          <View style={styles.imgWrap}>
            <Image
              style={{ width: 50, height: 50, resizeMode: "cover" }}
              source={{ uri: `${cart?.items[0].product.product_image}` }}
            />
          </View>
          <View style={styles.details}>
            <Text style={styles.text} numberOfLines={2}>
              {cart?.items[0]?.product.name}
            </Text>
            {/* <Text style={styles.text1} numberOfLines={2}>
              Variant:{cart?.items[0].variant}
            </Text> */}
            <View style={styles.rateCon}>
              {cart?.items[0].price ? (
                <>
                  <View style={styles.priceCon}>
                    <Text
                      style={
                        cart?.items[0]?.sale_price
                          ? styles.textPricePromo
                          : styles.textPrice
                      }
                    >
                      ₱
                      {parseFloat(cart?.items[0].price).toLocaleString("en-US")}
                    </Text>
                  </View>
                </>
              ) : (
                <Text>No price </Text>
              )}
              <Text style={styles.text1} numberOfLines={2}>
                Quantity: {cart?.items[0].quantity}
              </Text>
            </View>
          </View>
        </View>
        <View style={styles.form}>
          <Text style={styles.text2}>Reason for Returning:</Text>
          <TextInput
            style={styles.input}
            onChangeText={(e) => {
              setreason(e);
            }}
            //   value={email}
            multiline={true}
            numberOfLines={4}
            editable={success === true ? false : true}
            // placeholder="reason for returning"
            // keyboardType="numeric"
          />
        </View>
        <View style={styles.form}>
          <Text style={styles.text2}>Supporting files:</Text>
          <View style={styles.accountPrev}>
            {selectedImages[0] ? (
              <Image
                style={{
                  width: 100,
                  height: 100,
                  resizeMode: "cover",
                  borderWidth: 1,
                  borderColor: "#eee",
                  // borderRadius: 100,
                  marginHorizontal: 10,
                }}
                source={{
                  uri: selectedImages[0].imageFile.uri,
                }}
              />
            ) : null}
            {selectedImages[1] ? (
              <Image
                style={{
                  width: 100,
                  height: 100,
                  resizeMode: "cover",
                  borderWidth: 1,
                  borderColor: "#eee",
                  // borderRadius: 100,
                  marginHorizontal: 10,
                }}
                source={{
                  uri: selectedImages[1].imageFile.uri,
                }}
              />
            ) : null}
            {selectedImages?.length > 2 ? (
              <Text style={styles.text1}>
                {selectedImages?.length - 2} more
              </Text>
            ) : null}
            <TouchableOpacity
              style={styles.accountPrevWrap}
              disabled={success === true ? true : false}
              onPress={() => {
                selectImage();
              }}
            >
              {/* {selectedImage ? (
             
              ) : ( */}
              <View style={styles.upBtn}>
                <FontAwesomeIcon icon={faCamera} size={24} color={"#9c9c9c"} />
              </View>
              {/* )} */}

              {/* <View style={styles.editprof}>
              <FontAwesomeIcon icon={faEdit} size={24} color={"#333"} />
            </View> */}
            </TouchableOpacity>
          </View>
        </View>
        {success === true ? (
          <Text style={styles.btnTxt1}>
            Successfully sent your refund request!
          </Text>
        ) : success === false ? (
          <Text style={styles.btnTxt1}>
            Failed to submit, An error has occured, Please try again later!
          </Text>
        ) : (
          <TouchableOpacity style={styles.btn} onPress={() => ReturnSubmit()}>
            {loading === true ? (
              <ActivityIndicator size="large" color="#ececec" />
            ) : (
              <Text style={styles.btnTxt}>Submit</Text>
            )}
          </TouchableOpacity>
        )}
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    margin: 5,
    borderRadius: 10,
    borderColor: "#dddd",
    borderWidth: 1,
    overflow: "hidden",
    // flexDirection: "row",
    // padding: 10,
    backgroundColor: "#ffffff",
    // height: "60%",
  },
  wrapper: {
    margin: 10,
    marginBottom: 10,
    justifyContent: "space-between",
    alignItems: "center",
  },
  prodwrapper: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    borderWidth: 1,
    overflow: "hidden",
    borderColor: "#dddd",
    borderRadius: 10,
    padding: 10,
    marginTop: 20,
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 10,
  },
  textPrice: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  details: {
    width: "80%",
  },
  btn: {
    backgroundColor: "#ffaa00",
    paddingHorizontal: 55,
    width: "90%",
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 10,
    borderRadius: 15,
  },
  btnTxt: {
    fontSize: 15,
    color: "#fafafa",
    fontWeight: "600",
  },
  btnTxt1: {
    fontSize: 15,
    color: "#1b1b1b",
    fontWeight: "600",
    marginBottom: 10,
  },
  text: {
    fontSize: 13,
  },
  text1: {
    fontSize: 10,
    color: "#b4b4b4",
  },
  text2: {
    fontSize: 13,
    color: "#3b3b3b",
    marginLeft: 11,
    marginTop: 20,
  },
  text4: {
    fontSize: 18,
    color: "#3b3b3b",
    marginLeft: 11,
    marginTop: 20,
    fontWeight: "600",
    alignSelf: "center",
  },
  form: {
    width: "100%",
  },
  input: {
    maxHeight: 100,

    width: "95%",
    margin: 12,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
  },
  accountPrev: {
    marginBottom: 25,
    // width: 158,
    width: "100%",
    justifyContent: "center",
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
  },
  accountPrevWrap: {
    borderWidth: 4,
    borderStyle: "dashed",
    borderColor: "#ffaa00c0",
    padding: 10,
    margin: 10,
  },
  upBtn: {
    padding: 20,
  },
});

export default ReturnForm;
