import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation } from "@react-navigation/native";
import React, { memo, useRef, useState } from "react";
import {
  Dimensions,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import CompletedCard from "../../components/profile/my_purchases/CompletedCard";
import MasonryList from "@react-native-seoul/masonry-list";
import { checkOut } from "../../constants/checkout";
import ToPayCard from "../../components/profile/my_purchases/ToPay";
import ToShipCard from "../../components/profile/my_purchases/ToShip";
import ToReceiveCard from "../../components/profile/my_purchases/ToReceive";
import { useEffect } from "react";
import { get_orders_by_customer } from "../../services/api/controllers/order";
// import { user } from "../../constants/user";
import AsyncStorage from "@react-native-async-storage/async-storage";

const Tab = createMaterialTopTabNavigator();

function ToPay({ route }) {
  const { purchase } = route.params;
  // const cartPurchases = purchase.cartItems.filter(purchase => purchase.status === "CART");

  // console.log(purchase?.filter((item) => item.status === "CART"));
  const purch = purchase?.filter(
    (item) => item.status === "TO PAY" || item.status === "To Pay"
    // (item) => item.status === "Cart" || item.status === "CART"
  );
  const [product, setProduct] = useState(purch ?? []);
  const [isEndReached, setEndReached] = useState(false);
  const scrollViewRef = useRef(null);
  const [item1, setItem1] = useState(20);
  const [prod, setProd] = useState([]);
  console.log(item1);
  const initialProd = () => {
    const init = product?.slice(0, item1) ?? [];
    setProd(init);
  };

  useEffect(() => {
    initialProd();
  }, [product, item1]);

  const addProd = () => {
    if (item1 <= purch?.length) {
      const newArrayProd = [...prod, ...product?.slice(item1, item1 + 10)];
      setProd(newArrayProd);
      setItem1(item1 + 10); // Update item1 for the next batch
      setEndReached(false);
    }
  };
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;

    if (isAtEnd && !isEndReached) {
      setEndReached(true);
      addProd();
    }
  };
  return (
    <ScrollView
      style={styles.tabCon}
      ref={scrollViewRef}
      onScroll={handleScroll}
    >
      <MasonryList
        data={prod ?? []}
        keyExtractor={(item, i) => item?._id ?? i}
        style={styles.list}
        numColumns={1}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => <ToPayCard cart={item} />}
        containerStyle={styles.container1}
        contentContainerStyle={styles.content}
        onEndReachedThreshold={0.1}
      />
    </ScrollView>
  );
}
function ToShip({ route }) {
  const { purchase } = route.params;
  const purch = purchase?.filter(
    (item) => item.status === "TO SHIP" || item.status === "To Ship"
  );

  const [product, setProduct] = useState(purch ?? []);
  const [isEndReached, setEndReached] = useState(false);
  const scrollViewRef = useRef(null);
  const [item1, setItem1] = useState(20);
  const [prod, setProd] = useState([]);
  console.log(item1);
  const initialProd = () => {
    const init = product?.slice(0, item1) ?? [];
    setProd(init);
  };

  useEffect(() => {
    initialProd();
  }, [product, item1]);

  const addProd = () => {
    if (item1 <= purch?.length) {
      const newArrayProd = [...prod, ...product?.slice(item1, item1 + 10)];
      setProd(newArrayProd);
      setItem1(item1 + 10); // Update item1 for the next batch
      setEndReached(false);
    }
  };
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;

    if (isAtEnd && !isEndReached) {
      setEndReached(true);
      addProd();
    }
  };
  return (
    <ScrollView
      style={styles.tabCon}
      ref={scrollViewRef}
      onScroll={handleScroll}
    >
      <MasonryList
        data={prod ?? []}
        keyExtractor={(item) => item.id}
        style={styles.list}
        numColumns={1}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => <ToShipCard cart={item} />}
        containerStyle={styles.container1}
        contentContainerStyle={styles.content}
        onEndReachedThreshold={0.1}
      />
    </ScrollView>
  );
}

function ToReceive({ route }) {
  const { purchase } = route.params;
  const purch = purchase?.filter(
    (item) => item.status === "To Receive" || item.status === "TO RECEIVE"
  );
  const [product, setProduct] = useState(purch ?? []);
  const [isEndReached, setEndReached] = useState(false);
  const scrollViewRef = useRef(null);
  const [item1, setItem1] = useState(20);
  const [prod, setProd] = useState([]);
  console.log(item1);
  const initialProd = () => {
    const init = product?.slice(0, item1) ?? [];
    setProd(init);
  };

  useEffect(() => {
    initialProd();
  }, [product, item1]);

  const addProd = () => {
    if (item1 <= purch?.length) {
      const newArrayProd = [...prod, ...product?.slice(item1, item1 + 10)];
      setProd(newArrayProd);
      setItem1(item1 + 10); // Update item1 for the next batch
      setEndReached(false);
    }
  };
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;

    if (isAtEnd && !isEndReached) {
      setEndReached(true);
      addProd();
    }
  };
  return (
    <ScrollView
      style={styles.tabCon}
      ref={scrollViewRef}
      onScroll={handleScroll}
    >
      <MasonryList
        data={prod ?? []}
        keyExtractor={(item) => item.id}
        style={styles.list}
        numColumns={1}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => <ToReceiveCard cart={item} />}
        containerStyle={styles.container1}
        contentContainerStyle={styles.content}
        onEndReachedThreshold={0.1}
      />
    </ScrollView>
  );
}

function Completed({ route }) {
  const { purchase } = route.params;
  const purch = purchase?.filter(
    (item) => item.status === "Completed" || item.status === "COMPLETED"
  );
  const [product, setProduct] = useState(purch ?? []);
  const [isEndReached, setEndReached] = useState(false);
  const scrollViewRef = useRef(null);
  const [item1, setItem1] = useState(20);
  const [prod, setProd] = useState([]);
  console.log(item1);
  const initialProd = () => {
    const init = product?.slice(0, item1) ?? [];
    setProd(init);
  };

  useEffect(() => {
    initialProd();
  }, [product, item1]);

  const addProd = () => {
    if (item1 <= purch?.length) {
      const newArrayProd = [...prod, ...product?.slice(item1, item1 + 10)];
      setProd(newArrayProd);
      setItem1(item1 + 10); // Update item1 for the next batch
      setEndReached(false);
    }
  };
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;

    if (isAtEnd && !isEndReached) {
      setEndReached(true);
      addProd();
    }
  };
  return (
    <ScrollView
      style={styles.tabCon}
      ref={scrollViewRef}
      onScroll={handleScroll}
    >
      <MasonryList
        data={prod ?? []}
        keyExtractor={(item) => item.id}
        style={styles.list}
        numColumns={1}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => <CompletedCard cart={item} />}
        containerStyle={styles.container1}
        contentContainerStyle={styles.content}
        onEndReachedThreshold={0.1}
      />
    </ScrollView>
  );
}
const MyPurchases = ({ route }) => {
  const navigation = useNavigation();
  const [purchase, setpurchase] = useState(null);
  const [purchaseSort, setpurchaseSort] = useState(null);
  const [load, setload] = useState(true);
  const [user, setuser] = useState([]);

  const { tab } = route.params ?? "ToPay";

  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        console.log(pass);
        get_orders_by_customer({
          id: userDataArray[0]?._id,
        })
          .then((result) => {
            console.log("result" + result.data);

            if (result.error) {
              setError(result.error);
            } else {
              setpurchase(result.data);
              //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//

              const purchaseSorted = result.data?.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
                // }
                // }

                // setload(false);
                return acc;
              }, []);
              setpurchaseSort(purchaseSorted);
              console.log(purchaseSorted);
              setload(false);
            }
          })
          .catch((error) => {
            setError(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  useEffect(() => {
    // Fetch vendors and update the state
    // setload(true)
  }, []);
  useEffect(() => {
    //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//
    // const purchaseSorted = purchase?.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;
    // }, []);
    // setpurchaseSort(purchaseSorted);
  }, [purchase]);

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => navigation.navigate("Home")}
          style={styles.backIcon}
        >
          <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
        </TouchableOpacity>
        <Text style={styles.headerText}>My Purchases</Text>
      </View>

      <View style={styles.wrapper}>
        {load === false ? (
          <Tab.Navigator
            initialRouteName={tab ?? "ToPay"}
            scrollEnabled={true} // Set scrollEnabled to true to enable horizontal scrolling
            screenOptions={{
              tabBarScrollEnabled: true, // Make sure to set this to true as well

              // Adjust the width of each tab as needed
              tabBarIndicatorStyle: { backgroundColor: "#ffaa00" }, // Customize the indicator style
            }}
          >
            <Tab.Screen
              name="ToPay"
              component={ToPay}
              options={{ tabBarLabel: "To Pay" }}
              initialParams={{
                purchase: purchase.sort((a, b) => {
                  const dateA = new Date(a.updatedAt);
                  const dateB = new Date(b.updatedAt);
                  return dateB - dateA;
                }),
              }}
            />
            <Tab.Screen
              name="ToShip"
              component={ToShip}
              options={{ tabBarLabel: "To Ship" }}
              initialParams={{
                purchase: purchase.sort((a, b) => {
                  const dateA = new Date(a.updatedAt);
                  const dateB = new Date(b.updatedAt);
                  return dateB - dateA;
                }),
              }}
            />
            <Tab.Screen
              name="ToReceive"
              component={ToReceive}
              options={{ tabBarLabel: "To Receive" }}
              initialParams={{
                purchase: purchase.sort((a, b) => {
                  const dateA = new Date(a.updatedAt);
                  const dateB = new Date(b.updatedAt);
                  return dateB - dateA;
                }),
              }}
            />
            <Tab.Screen
              name="Completed"
              component={Completed}
              options={{ tabBarLabel: "Completed" }}
              initialParams={{
                purchase: purchase.sort((a, b) => {
                  const dateA = new Date(a.updatedAt);
                  const dateB = new Date(b.updatedAt);
                  return dateB - dateA;
                }),
              }}
            />
          </Tab.Navigator>
        ) : null}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffff",
    width: "100%",
    height: "100%",
  },
  wrapper: {
    height: "95%",
    width: "100%",
    justifyContent: "center",
    // alignItems:'center'
    marginBottom: 20,
  },
  header: {
    alignItems: "center",
    width: "100%",
    top: 0,
    paddingLeft: 15,
    flexDirection: "row",
    borderColor: "#ddd",
    paddingBottom: 15,
    borderBottomWidth: 1,
  },
  headerText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 25,
  },
  tabCon: {
    width: "100%",
    height: "100%",
  },
  list: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    padding: 5,
  },
});

// export default MyPurchases;
export default memo(MyPurchases);
