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 { useNavigation } from "@react-navigation/native";
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import MasonryList from "@react-native-seoul/masonry-list";
import ProductCard from "../../components/profile/view-history/ProductCard";
import ShopCard from "../../components/profile/view-history/ShopCard";
import { favorite } from "../../constants/favorites";
import Checkbox from "expo-checkbox";
import DeleteConfirmationModal from "../../components/DeleteConfirmationModal";
// import { products } from "../../constants/product";
const Tab = createMaterialTopTabNavigator();


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

  const [isModalVisible, setModalVisible] = useState(false);

  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([]);
      setall(false)
    } else {
      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>
      {products ? (
        <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 } = route.params;
  const [prodLike, setprodLike] = useState([]);
  const [all, setall] = useState(false);
  const [product, setproduct] = useState(shops ?? []);
  const [isModalVisible, setModalVisible] = useState(false);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };
  console.log(prodLike);
  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([]);
      setall(false)

    } else {
      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}
            />
          )}
          containerStyle={styles.container1}
          contentContainerStyle={styles.content}
          onEndReachedThreshold={0.1}
        />
      ) : null}
        <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItem}
      />
    </View>
  );
}
const ViewHistory = () => {
  const navigation = useNavigation();
  const products = favorite?.find((item) => item.type === "products")?.contents;
  const shops = favorite?.find((item) => item.type === "vendors")?.contents;

  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}>Recently Viewed</Text>
      </View>

      <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: products }}
          />
          <Tab.Screen
            name="Vendors"
            component={Vendors}
            options={{ tabBarLabel: "Vendors" }}
            initialParams={{ shops: shops }}
          />
        </Tab.Navigator>
      </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%",
  },
  actions: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
  },
  list: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    padding: 5,
  },
  list: {
    width: "100%",
    // backgroundColor: "#fff",
  },
  content: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",

    // backgroundColor: "#ffaa00",
  },
  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 ViewHistory;
