import {
  faArrowLeft,
  faDeleteLeft,
  faTrash,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  Dimensions,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import MasonryList from "@react-native-seoul/masonry-list";
import ProductCard from "../../components/profile/my-favorite/ProductCard";
import ShopCard from "../../components/profile/my-favorite/ShopCard";
import { favorite } from "../../constants/favorites";
import Checkbox from "expo-checkbox";
// import { products } from "../../constants/product";
const Tab = createMaterialTopTabNavigator();
import Modal from "react-native-modal";
import DeleteConfirmationModal from "../../components/DeleteConfirmationModal";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
  get_customer,
  update_customer,
} from "../../services/api/controllers/customers";

function Products({ route }) {
  const { products } = route.params;
  const [prodLike, setprodLike] = useState([]);
  const [all, setall] = useState(false);
  const [product, setproduct] = useState(products ?? []);
  const isFocused = useIsFocused();

  console.log(products + "ey");
  // console.log(prodLike);
  const [isModalVisible, setModalVisible] = useState(false);

  const [user, setuser] = useState([]);
  const [error, seterror] = useState([]);
  const [liked, setliked] = useState([]);
  const [load, setload] = useState(false);

  // useEffect(() => {
  //   // setrefresh(isrefresh);
  //   AsyncStorage.getItem("userData")
  //     .then((pass) => {
  //       // console.log("mm "+pass._id);
  //       const userDataArray = JSON.parse(pass);
  //       setuser(userDataArray);
  //       get_customer({ id: userDataArray[0]?._id })
  //         .then((result) => {
  //           // console.log(result.data);

  //           if (result.error) {
  //             seterror(result.error);
  //           } else {
  //             // const exists = result?.data?.favorites?.some((prod) => prod._id === product?._id);
  //             // console.log( exists)
  //             // if (exists) {
  //             // console.log( "heyyyy")

  //             //   setisLiked(true);
  //             // }
  //             setliked(result?.data?.favorites);
  //             setproduct(result?.data?.favorites.products);

  //             setload(true);
  //           }
  //         })
  //         .catch((error) => {
  //           // setError(error.message);
  //           console.log(error.message);
  //         })
  //         .finally(() => {
  //           // setprodIsLoading(false); // Set loading to false when done loading
  //         });
  //     })
  //     .catch((error) => {
  //       console.log(error + "weeewwww");
  //     });
  //   // console.log("get cutomer add :" + user[0]?.login_id);
  // }, []);
  useEffect(() => {
    // setrefresh(isrefresh);
    AsyncStorage.getItem("userData")
      .then((pass) => {
        // console.log("mm "+pass._id);
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        get_customer({ id: userDataArray[0]?._id })
          .then((result) => {
            // console.log(result.data);

            if (result.error) {
              seterror(result.error);
            } else {
              // const exists = result?.data?.favorites?.some((prod) => prod._id === product?._id);
              // console.log( exists)
              // if (exists) {
              // console.log( "heyyyy")

              //   setisLiked(true);
              // }
              setliked(result?.data?.favorites);
              setproduct(result?.data?.favorites.products?.reverse());

              setload(true);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    // console.log("get cutomer add :" + user[0]?.login_id);
  }, [isFocused]);
  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  const likeClick = (e) => {
    setprodLike((prevLikes) => {
      // Check if e is already included in prodLike
      if (prevLikes.includes(e) && e != "all") {
        // If e is already in the array, remove it
        return prevLikes.filter((item) => item !== e);
      } else {
        // If e is not in the array, add it to the beginning
        return [e, ...prevLikes];
      }
    });
  };
  const deleteItem = () => {
    toggleModal();

    if (all === true) {
      setproduct([]);
      // const updatedFavorites = liked.map((favorite) => {
      //   const updatedProduct = [];
      //   return { ...favorite, products: updatedProduct };
      // });
      update_customer({
        id: user[0]._id,
        body: {
          favorites: {
            products: [],
            vendors: liked?.vendors,
          },
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
      setall(false);
    } else {
      // const updatedFavorites = liked.map((favorite) => {
      const updatedProduct = liked.products.filter(
        (item, index) => !prodLike.includes(index)
      );
      //   return { ...favorite, products: updatedProduct };
      // });
      update_customer({
        id: user[0]._id,
        body: {
          favorites: {
            products: updatedProduct,
            vendors: liked.vendors,
          },
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
      setproduct((prevProduct) => {
        // Filter the 'prevProduct' array to exclude items with indices in 'prodLike'
        const updatedProduct = prevProduct.filter(
          (item, index) => !prodLike.includes(index)
        );
        return updatedProduct;
      });
      setprodLike([]);
    }
  };
  return (
    <View style={styles.tabCon}>
      <View style={styles.actions}>
        <Checkbox value={all} onValueChange={() => setall((prev) => !prev)} />
        <TouchableOpacity
          onPress={() => {
            toggleModal();
          }}
        >
          <FontAwesomeIcon icon={faTrash} />
        </TouchableOpacity>
      </View>
      {product ? (
        <MasonryList
          data={product}
          keyExtractor={(item) => item.id}
          style={styles.list}
          numColumns={2}
          showsVerticalScrollIndicator={false}
          renderItem={({ item, i }) => (
            <ProductCard
              like={likeClick}
              liked={prodLike}
              index={i}
              product={item}
              all={all}
            />
          )}
          containerStyle={styles.container1}
          contentContainerStyle={styles.content}
          onEndReachedThreshold={0.1}
        />
      ) : null}
      <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItem}
      />
    </View>
  );
}
function Vendors({ route }) {
  const { shops, prods } = route.params;
  const [prodLike, setprodLike] = useState([]);
  const [all, setall] = useState(false);
  const [shopProd, setshopProd] = useState([]);
  const isFocused = useIsFocused();

  const [product, setproduct] = useState(shops ?? []);
  const [isModalVisible, setModalVisible] = useState(false);

  const [user, setuser] = useState([]);
  const [error, seterror] = useState([]);
  const [liked, setliked] = useState([]);
  const [load, setload] = useState(false);
  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };
  console.log(prodLike);
  // useEffect(() => {
  //   // setrefresh(isrefresh);
  //   AsyncStorage.getItem("userData")
  //     .then((pass) => {
  //       // console.log("mm "+pass._id);
  //       const userDataArray = JSON.parse(pass);
  //       setuser(userDataArray);
  //       get_customer({ id: userDataArray[0]?._id })
  //         .then((result) => {
  //           // console.log(result.data);

  //           if (result.error) {
  //             seterror(result.error);
  //           } else {
  //             setliked(result?.data?.favorites);
  //             setload(true);
  //           }
  //         })
  //         .catch((error) => {
  //           // setError(error.message);
  //           console.log(error.message);
  //         })
  //         .finally(() => {
  //           // setprodIsLoading(false); // Set loading to false when done loading
  //         });
  //     })
  //     .catch((error) => {
  //       console.log(error + "weeewwww");
  //     });
  //   // console.log("get cutomer add :" + user[0]?.login_id);
  // }, []);
  useEffect(() => {
    // setrefresh(isrefresh);
    AsyncStorage.getItem("userData")
      .then((pass) => {
        // console.log("mm "+pass._id);
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        get_customer({ id: userDataArray[0]?._id })
          .then((result) => {
            // console.log(result.data);

            if (result.error) {
              seterror(result.error);
            } else {
              setliked(result?.data?.favorites);
              setproduct(result?.data?.favorites.vendors?.reverse());
              setload(true);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    // console.log("get cutomer add :" + user[0]?.login_id);
  }, [isFocused]);

  const likeClick = (e) => {
    setprodLike((prevLikes) => {
      // Check if e is already included in prodLike
      if (prevLikes.includes(e) && e != "all") {
        // If e is already in the array, remove it
        return prevLikes.filter((item) => item !== e);
      } else {
        // If e is not in the array, add it to the beginning
        return [e, ...prevLikes];
      }
    });
  };
  const deleteItem = () => {
    toggleModal();

    if (all === true) {
      setproduct([]);
      // const updatedFavorites = liked.map((favorite) => {
      //   const updatedProduct = [];
      //   return { ...favorite, vendors: updatedProduct };
      // });
      update_customer({
        id: user[0]._id,
        body: {
          favorites: {
            products: liked.products,
            vendors: [],
          },
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
      setall(false);
    } else {
      // const updatedFavorites = liked.map((favorite) => {
      const updatedProduct = liked.vendors.filter(
        (item, index) => !prodLike.includes(index)
      );
      //   return { ...favorite, vendors: updatedProduct };
      // });
      update_customer({
        id: user[0]._id,
        body: {
          favorites: {
            products: liked.products,
            vendors: updatedProduct,
          },
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
      setproduct((prevProduct) => {
        // Filter the 'prevProduct' array to exclude items with indices in 'prodLike'
        const updatedProduct = prevProduct.filter(
          (item, index) => !prodLike.includes(index)
        );
        return updatedProduct;
      });
      setprodLike([]);
    }
  };
  return (
    <View style={styles.tabCon}>
      <View style={styles.actions}>
        <Checkbox value={all} onValueChange={() => setall((prev) => !prev)} />
        <TouchableOpacity
          onPress={() => {
            toggleModal();
          }}
        >
          <FontAwesomeIcon icon={faTrash} />
        </TouchableOpacity>
      </View>
      {shops ? (
        <MasonryList
          data={product ?? null}
          keyExtractor={(item) => item.id}
          style={styles.list}
          numColumns={1}
          showsVerticalScrollIndicator={false}
          renderItem={({ item, i }) => (
            <ShopCard
              product={item}
              like={likeClick}
              liked={prodLike}
              index={i}
              all={all}
              prods={prods}
            />
          )}
          containerStyle={styles.container1}
          contentContainerStyle={styles.content}
          onEndReachedThreshold={0.1}
        />
      ) : null}
      <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItem}
      />
    </View>
  );
}
const MyFavorites = ({ prod }) => {
  const navigation = useNavigation();
  const [shopProd, setshopProd] = useState([]);

  // const products = favorite?.find((item) => item.type === "products")?.contents;

  const shops = favorite?.find((item) => item.type === "vendors")?.contents;

  const [user, setuser] = useState([]);
  const [error, seterror] = useState([]);
  const [liked, setliked] = useState([]);
  const [load, setload] = useState(false);

  useEffect(() => {
    // setrefresh(isrefresh);
    AsyncStorage.getItem("userData")
      .then((pass) => {
        // console.log("mm "+pass._id);
        const userDataArray = JSON.parse(pass);
        // console.log(pass)
        setuser(userDataArray);
        get_customer({ id: userDataArray[0]?._id })
          .then((result) => {
            // console.log(result.data);

            if (result.error) {
              seterror(result.error);
            } else {
              // const exists = result?.data?.favorites?.some((prod) => prod._id === product?._id);
              // console.log( exists)
              // if (exists) {
              // console.log( "heyyyy")

              //   setisLiked(true);
              // }
              setliked(result?.data?.favorites);
              // console.log(result.data.favorites);
              // console.log(result?.data?.favorites?.products);

              setload(true);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    // console.log("get cutomer add :" + user[0]?.login_id);
  }, []);
  // console.log(liked[0]?.products+"added")
  const revereseProd = liked?.products?.reverse();
  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 Favorite</Text>
      </View>

      {load ? (
        <View style={styles.wrapper}>
          <Tab.Navigator
            scrollEnabled={true} // Set scrollEnabled to true to enable horizontal scrolling
            screenOptions={{
              tabBarIndicatorStyle: { backgroundColor: "#ffaa00" }, // Customize the indicator style
            }}
          >
            <Tab.Screen
              name="Products"
              component={Products}
              options={{ tabBarLabel: "Products" }}
              initialParams={{ products: revereseProd }}
            />
            <Tab.Screen
              name="Vendors"
              component={Vendors}
              options={{ tabBarLabel: "Vendors" }}
              initialParams={{ shops: liked?.vendors.reverse(), prods: prod }}
            />
          </Tab.Navigator>
        </View>
      ) : null}
    </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%",
  },
  actions: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
  },
  list: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    padding: 5,
  },
  list: {
    width: "100%",
  },
  content: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  buttons: {
    position: "absolute",
    flexDirection: "row",
    bottom: 0,
  },
  btnCancel: {
    color: "#ff0000",
    padding: 10,
  },
  btnCancelText: {
    color: "#ff0000",
    padding: 10,
  },
  btnConfirm: {
    color: "#ff0000",
    padding: 10,
  },
  btnConfirmText: {
    color: "#001aff",
    padding: 10,
  },
});

export default MyFavorites;
