import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Dimensions,
  RefreshControl,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import MasonryList from "@react-native-seoul/masonry-list";
import CartCard from "../../components/cart/CartCard";
import Checkbox from "expo-checkbox";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import {
  faArrowLeft,
  faDeleteLeft,
  faTrash,
} from "@fortawesome/free-solid-svg-icons";
import DeleteConfirmationModal from "../../components/DeleteConfirmationModal";
// import { cart } from "../../constants/cart";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import {
  delete_order,
  get_order,
  get_orders_by_customer,
} from "../../services/api/controllers/order";
// import { user } from "../../constants/user";
import { ScrollView } from "react-native-gesture-handler";
import AsyncStorage from "@react-native-async-storage/async-storage";
const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height;

const Cart = ({ cartList, refresh }) => {
  const [cartSort, setcartSort] = useState([]);
  const [all, setall] = useState(false);
  const [shopSelected, setshopSelected] = useState([]);
  const [quantityChange, setquantityChange] = useState([]);

  const [load, setload] = useState(false);

  const [cart, setcart] = useState([]);
  const [totalPrice, settotalPrice] = useState(0);
  const [error, setError] = useState(false);

  const [checkoutItems, setCheckOutItems] = useState([]);

  const [isModalVisible, setModalVisible] = useState(false);
  const navigation = useNavigation();
  const [refreshing, setRefreshing] = useState(true);
  const [user, setuser] = useState([]);
  const isFocused = useIsFocused();
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    AsyncStorage.getItem("userData")
      .then((pass) => {
        if (pass !== null) {
          const userDataArray = JSON.parse(pass);
          setuser(userDataArray);
          console.log(userDataArray[0]?._id);
          get_orders_by_customer({
            id: userDataArray[0]?._id,
          })
            .then((result) => {
              if (result.error) {
                setError(result.error);
              } else {
                setcart(result.data ?? []);
              }
            })
            .catch((error) => {
              setError(error.message);
              setcart([]);
            })
            .finally(() => {
              // setprodIsLoading(false); // Set loading to false when done loading
            });
          console.log(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  useEffect(() => {
    // Simulate a delay for the purpose of this example
    setload(true);
    setTimeout(() => {
      // After the refresh logic is complete, set refreshing state to false
      setload(false);
    }, 200); // 2000 milliseconds (2 seconds) delay for demonstration
  }, []);
  useEffect(() => {
    if (quantityChange) {
      setload(true);

      get_orders_by_customer({
        id: user[0]?._id,
      })
        .then((result) => {
          //  console.log("result" + result);

          if (result.error) {
            setError(result.error);
          } else {
            setcart(result.data);
            setload(false);
          }
        })
        .catch((error) => {
          setError(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
    }
  }, [quantityChange]);
  useEffect(() => {
    console.log("focused on cart");
    // setRefreshing(false);

    if (isFocused) {
      setload(true);

      AsyncStorage.getItem("userData")
        .then((pass) => {
          if (pass !== null) {
            const userDataArray = JSON.parse(pass);
            setuser(userDataArray);
            console.log(userDataArray[0]?._id);
            get_orders_by_customer({
              id: userDataArray[0]?._id,
            })
              .then((result) => {
                if (result.error) {
                  // setRefreshing(true);
                  setload(false);

                  setError(result.error);
                } else {
                  setcart(result.data ?? []);
                  setload(false);
                }
              })
              .catch((error) => {
                setError(error.message);
                setcart([]);
              })
              .finally(() => {
                // setprodIsLoading(false); // Set loading to false when done loading
              });
            console.log(pass);
          } else {
            setcart([]);

            setload(false);
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
    }
  }, [isFocused]);
  const handleRefresh = () => {
    setRefreshing(true);
    setload(true);
    console.log("refreshing");
    // Simulate a delay for the purpose of this example
    setTimeout(() => {
      // After the refresh logic is complete, set refreshing state to false
      setRefreshing(false);
      setload(false);
    }, 2000); // 2000 milliseconds (2 seconds) delay for demonstration
  };
  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };
  console.log(cartSort);
  // useEffect(() => {
  //  setcartSort(cartSort)
  // }, [cartSort])

  useEffect(() => {
    // Fetch vendors and update the state
  }, []);
  useEffect(() => {
    // Fetch vendors and update the state
    if (refreshing) {
      setload(true);
      get_orders_by_customer({
        id: user[0]?._id,
      })
        .then((result) => {
          //  console.log("result" + result);

          if (result.error) {
            setError(result.error);
          } else {
            setcart(result.data);
            setload(false);
          }
        })
        .catch((error) => {
          setError(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
    }
  }, [refreshing]);
  const selectAll = () => {
    setcartSort((prevCartList) => {
      // Create a copy of the cartList to avoid mutating the original state
      const newCartList = [...prevCartList];

      // Set 'selected' property to true for all shops and products
      newCartList.forEach((shop) => {
        shop.selected = all;
        shop.cartItems.forEach((product) => {
          product.selected = all;
        });
      });

      return newCartList;
    });
  };

  //  state variable 'all' triggers the useEffect
  useEffect(() => {
    selectAll();
  }, [all]);

  const shopLiked = (shopIndex) => {
    setcartSort((prevCartList) => {
      //  copy of the cartList to avoid mutating the original state
      const newCartList = [...prevCartList];

      // Toggle the 'selected' property of the shop
      newCartList[shopIndex].selected = !newCartList[shopIndex].selected;

      // Toggle the 'selected' property of all products in the shop
      newCartList[shopIndex].cartItems.forEach((product) => {
        product.selected = newCartList[shopIndex].selected;
      });

      return newCartList;
    });
  };
  const shopProdLike = (shopIndex, prodIndex) => {
    setcartSort((prevCartList) => {
      // Create a copy of the cartList to avoid mutating the original state
      const newCartList = [...prevCartList];

      // Toggle the 'selected' property of the product at the specified shopIndex and prodIndex
      newCartList[shopIndex].cartItems[prodIndex].selected =
        !newCartList[shopIndex].cartItems[prodIndex].selected;

      // Set the shop's 'selected' property to false
      newCartList[shopIndex].selected = false;

      return newCartList;
    });
  };
  const checkOut = () => {
    // Create a new array 'checkOutItems' by filtering the cartSort
    const checkOutItems = cartSort
      ?.map((shop) => {
        const filteredCartItems = shop.cartItems.filter(
          (item) => item.selected
        );
        return { ...shop, cartItems: filteredCartItems };
      })
      .filter((shop) => shop?.cartItems?.length > 0);

    // Set the new state for 'checkOutItems'
    setCheckOutItems(checkOutItems);

    // Navigate only if there are items in the shops
    if (checkOutItems?.length > 0) {
      navigation.navigate("CheckOutMultiple", {
        product: checkOutItems,
        // orderId: result.data._id,
      });
    }

    console.log(checkOutItems);
  };

  useEffect(() => {
    //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//
    const cartSorted = cart?.reverse()?.reduce((acc, item) => {
      const shopId = item.items[0].vendor_id;
      const shopName = item.items[0].vendor_name;

      const existingShop = acc.find((shop) => shop.shopId === shopId);
      console.log("shop: " + shopName);
      if (item.status === "CART") {
        if (existingShop) {
          // Shop already exists, add the item to its cartItems array
          existingShop.cartItems.push({ ...item, selected: false }); // Initialize selected to false
        } else {
          // Shop doesn't exist, create a new shop object with selected:false
          acc.push({
            shopname: shopName,
            shopId: shopId,
            cartItems: [{ ...item, selected: false }],
            selected: false,
            shippingFee: 0,
          }); // Initialize selected to false
        }
      }

      return acc;
    }, []);
    setcartSort(cartSorted);
  }, [cart]);
  const calculateTotalPrice = () => {
    let total = 0;

    // Iterate through the cartSort to calculate the total price
    cartSort?.forEach((shop) => {
      let shopHasSelectedProducts = false; // Flag to check if the shop has selected products

      shop.cartItems.forEach((product) => {
        if (product.selected) {
          // Calculate the total price for the selected product
          let productTotal = 0;

          if (product.promo > 0) {
            // Apply promo discount if promo is greater than 0
            productTotal =
              product.regular_price *
              (1 - product.promo / 100) *
              product.quantity; // Assuming promo is in percentage (e.g., 30%)
          } else {
            // Otherwise, calculate total without promo discount
            productTotal =
              product.items[0].price * parseInt(product.items[0].quantity, 10);
          }

          // Add the product total to the overall total
          total += productTotal;

          // Set the flag to true if at least one product is selected in the shop
          shopHasSelectedProducts = true;
        }
      });

      if (shopHasSelectedProducts) {
        // Add the shipping fee for the shop if it has selected products
        total += shop.shippingFee;
      }
    });

    return parseFloat(total)?.toLocaleString("en-US");
  };

  // const quantityChange = (shopIndex, prodIndex, qty) => {
  //   setcartSort((prevCartList) => {
  //     // Create a copy of the cartSort to avoid mutating the original state
  //     const newCartList = [...prevCartList];

  //     // Update the quantity of the product at the specified shopIndex and prodIndex
  //     newCartList[shopIndex].cartItems[prodIndex].quantity = qty;

  //     return newCartList;
  //   });
  // };
  const deleteItems = () => {
    // setload(true);
    setRefreshing(false);
    toggleModal();
    // setcartSort((prevCartList) => {
    //   // Filter out selected shops
    //   const newCartList = prevCartList.filter((shop) => !shop.selected);

    //   // Update cartItems for shops that are not selected
    //   newCartList.forEach((shop) => {
    //     shop.cartItems = shop.cartItems.filter((product) => !product.selected);
    //   });

    //   // Remove shops with no cartItems
    //   const finalCartList = newCartList.filter(
    //     (shop) => shop?.cartItems?.length > 0
    //   );

    //   return finalCartList;
    // });
    const deletePromises = [];

    const newCartList = cartSort;

    // Update cartItems for shops that are not selected
    newCartList?.forEach((shop) => {
      shop.cartItems = shop.cartItems.filter((product) => product.selected);
    });

    // Remove shops with no cartItems
    // const finalCartList = newCartList.filter(
    //   (shop) => shop?.cartItems?.length > 0
    // );

    if (newCartList) {
      newCartList.forEach((order) => {
        // Loop through the items in each order's 'cartItems'
        order.cartItems.forEach((cartItem) => {
          // Construct the 'body' object for updating the order
          console.log(
            "I am here and the order cart items to delete is " + order.cartItems
          );
          // setload(true);

          const orderId = cartItem._id;
          // const orderName = cartItem.items[0].name;

          const deletePromise = delete_order({
            id: orderId,
          });

          deletePromises.push(deletePromise);
        });
      });

      Promise.all(deletePromises)
        .then((results) => {
          // Handle results of updating orders
          results.forEach((updateResult, index) => {
            if (updateResult.status === 200) {
              console.log(
                // `Order update id: ${updateResult.data} orderName: ${product[index].cartItems[0].items[0].name} orderId: ${product[index].cartItems[0]._id} amount: ${result.data.attributes.amount}`
                "deleted"
              );
              // setload(false);
              // setamount(result.data.attributes.amount);
              // setpaymessage(result.data.attributes.description);
              // setModalVisible(!modalVisible);
            } else {
              // console.log("Update order failed for order with ID:", product[index].cartItems[0]._id);
              ("failed");
            }
          });
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
          console.log("heyyyy finally");
          setRefreshing(true);
          // setload(true);

          // setload(false);
        });
    }

    console.log(cartSort);
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>CART</Text>
      </View>
      <View style={styles.actions}>
        <View style={{ flexDirection: "row" }}>
          <Checkbox value={all} onValueChange={() => setall((prev) => !prev)} />
          <Text style={{ marginLeft: 10 }}>Select All</Text>
        </View>
        <TouchableOpacity
          onPress={() => {
            toggleModal();
          }}
        >
          <FontAwesomeIcon icon={faTrash} />
        </TouchableOpacity>
      </View>
      {!load ? (
        <View style={styles.wrapper}>
          <MasonryList
            data={cartSort ?? []}
            keyExtractor={(item) => item.id}
            style={styles.list}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            onRefresh={() => handleRefresh()} // Add this line
            // refreshing={refreshing} // Add this line
            renderItem={({ item, i }) => (
              <CartCard
                all={all}
                index={i}
                shopLike={shopLiked}
                shopProdLike={shopProdLike}
                cart={item}
                quantityChange={setquantityChange}
                q={quantityChange}
              />
            )}
            containerStyle={styles.container1}
            contentContainerStyle={styles.content}
            onEndReachedThreshold={0.1}
          />
        </View>
      ) : (
        <ActivityIndicator size="large" color="#ffaa00" />
      )}
      <View style={styles.bottom}>
        <View style={styles.details}>
          <View style={styles.detailsTop}>
            <Text style={styles.detailsTopText}>Total Price : </Text>
            <Text style={styles.detailsTopTextPrice}>
              {" "}
              ₱{calculateTotalPrice()}
            </Text>
          </View>
        </View>
        <TouchableOpacity style={styles.checkout} onPress={() => checkOut()}>
          <Text style={styles.checkoutText}>CHECKOUT</Text>
        </TouchableOpacity>
      </View>
      <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItems}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffffff",
    paddingTop: 10,
    height: "100%",
    width: width,

    // height:height -70
  },
  header: {
    width: "100%",
    top: 0,
    height: 40,
    marginLeft: 15,
  },
  container1: {
    width: "100%",
  },

  actions: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
    paddingTop: 0,
  },
  content: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  list: {
    width: "100%",
  },
  headerText: {
    textAlign: "left",
    width: "100%",
    fontWeight: "600",
    fontSize: 16,
  },
  footer: {
    bottom: 0,
    width: "100%",
  },
  wrapper: {
    width: "100%",
    height: "90%",
    // justifyContent: "center",
    // alignItems: "center",
    padding: 5,
    paddingBottom: 60,
  },
  list: {
    width: "100%",
    height: "90%",
    // justifyContent: "center",
    // alignItems: "center",
  },
  card: {
    width: "100%",
    borderWidth: 1,
    borderColor: "#dddd",
    justifyContent: "center",
    padding: 15,
    paddingVertical: 10,
    borderRadius: 10,
    marginVertical: 2,
  },
  title: {
    fontSize: 16,
    fontWeight: "600",
  },
  body: {
    fontSize: 16,
    // fontWeight: "600",
    marginTop: 5,
  },
  date: {
    fontSize: 12,
    // fontWeight: "600",
    color: "#797979",
    marginTop: 10,
  },
  bottom: {
    position: "absolute",
    bottom: 0,
    backgroundColor: "#fff",
    width: "100%",
    justifyContent: "space-between",
    alignItems: "center",
    flexDirection: "row",
    borderTopWidth: 1,
    borderColor: "#dddd",
  },
  details: {
    padding: 10,
  },
  detailsTop: {
    // padding:10,
    flexDirection: "row",
  },
  detailsTopText: {
    color: "#363636",
    fontWeight: "600",
    fontSize: 14,
    letterSpacing: 0.5,
  },
  detailsTopTextPrice: {
    color: "#ffaa00",
    fontWeight: "600",
    fontSize: 16,
    letterSpacing: 0.5,
  },
  checkout: {
    backgroundColor: "#ffaa00",
    width: 150,
    justifyContent: "center",
    alignItems: "center",
    padding: 15,
  },
  checkoutText: {
    color: "#fff",
    fontWeight: "600",
    fontSize: 16,
    letterSpacing: 0.7,
  },
});
export default Cart;
