import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import React, { useEffect, useRef, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Dimensions,
  TouchableOpacity,
  TextInput,
} from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import SearchHeader from "../../components/search/Header";
import ProductCard from "../../components/search/ProductCard";
import ShopCard from "../../components/search/ShopCard";
import { favorite } from "../../constants/favorites";
import MasonryList from "@react-native-seoul/masonry-list";
import { search_product } from "../../services/api/controllers/product";
// import { TouchableOpacity } from "react-native-gesture-handler";
import { search_vendor } from "../../services/api/controllers/vendor";
const height = Dimensions.get("window").height;
import Modal from "react-native-modal";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { faFilter } from "@fortawesome/free-solid-svg-icons";
import { useIsFocused, useRoute } from "@react-navigation/native";
const deviceWidth = Dimensions.get("window").width;
const Tab = createMaterialTopTabNavigator();

function Products({ route }) {
  const { productsU, productAll } = route.params;
  const products = productsU?.results?.filter(
    (item) => item?.product?.product_type !== "variation"
  );
  // console.log(products);
  const [prodLike, setprodLike] = useState([]);
  const [all, setall] = useState(false);
  const [product, setproduct] = useState(products ?? []);
  const scrollViewRef = useRef(null);
  const [item, setitem] = useState(20);
  const [prod, setprod] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [isFilter, setisFilter] = useState(false);
  const [filterProd, setfilterProd] = useState([]);
  const [filterData, setfilterData] = useState([]);
  const [min, setmin] = useState(null);
  const [max, setmax] = useState(null);
  const [filtering, setfiltering] = useState(false);
  const [filterStart, setfilterStart] = useState(false);

  const [isEndReached, setEndReached] = useState(false);

  // const initialProd = () => {
  //   const init = product?.slice(0, item) ?? [];
  //   setprod(init);
  // };

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

  // const addProd = () => {
  //   if (item <= products?.length) {
  //     const newArrayProd = [...prod, ...product?.slice(item, item + 10)];
  //     setprod(newArrayProd);
  //     setitem(item + 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();
  //   }
  // };

  // const filterApply = () => {
  //   console.log("filtering");

  //   const filteredProduct = products; // Assuming products is an array
  //   let filteredProducts = [...filteredProduct]; // Create a copy of the products array

  //   if (min !== null || max !== null) {
  //     const minPrice = min ?? 0;
  //     const maxPrice = max ?? Number.MAX_VALUE;

  //     filteredProducts = filteredProducts.filter((product1) => {
  //       const regularPrice = parseInt(product1?.product?.regular_price) || 0;
  //       return (
  //         regularPrice >= parseInt(minPrice, 10) &&
  //         regularPrice <= parseInt(maxPrice, 10)
  //       );
  //     });
  //   }

  //   // Update state based on the filtered products
  //   if (filteredProducts.length > 0) {
  //     setproduct({ results: filteredProducts }); // Set filtered products (limiting to 20 items)
  //     console.log({ results: filteredProducts });
  //     setisFilter(true);
  //     setfiltering(true);
  //   } else {
  //     // setfiltering(true);
  //     setproduct(products ?? []); // Set original products if no filters applied (limiting to 20 items)
  //     setisFilter(false);
  //     // setfiltering(false);
  //   }
  //   setModalVisible(false);
  // };

  // useEffect(() => {
  //   if (filtering) {
  //     // console.log("Filtering Applied");
  //     setprod(product?.results?.slice(0, 20));
  //     // console.log("final prod" + prod);
  //     setfiltering(false);
  //   }
  // }, [filtering]);

  const initialProd = () => {
    const init = product?.slice(0, item) ?? [];
    setprod(init);
  };

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

  const addProd = () => {
    if (item <= products?.length) {
      const newArrayProd = [...prod, ...product?.slice(item, item + 10)];
      setprod(newArrayProd);
      setitem(item + 10);
      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();
    }
  };

  const filterApply = () => {
    console.log("filtering");

    let filteredProducts = [...products]; // Create a copy of the products array

    const minPrice = min === "" ? null : min; // Treat empty string as null for min
    const maxPrice = max === "" ? null : max; // Treat empty string as null for max

    if (minPrice !== null || maxPrice !== null) {
      filteredProducts = filteredProducts.filter((product1) => {
        const regularPrice = parseInt(product1?.product?.regular_price) || 0;
        return (
          regularPrice >= parseInt(minPrice || 0, 10) && // Use 0 if minPrice is null
          regularPrice <= parseInt(maxPrice || Number.MAX_VALUE, 10) // Use MAX_VALUE if maxPrice is null
        );
      });
    }

    // Update state based on the filtered products
    if (filteredProducts.length > 0) {
      setprod(filteredProducts.slice(0, 20)); // Display filtered products (limiting to 20 items)
      setisFilter(true);
      setfiltering(true);
    } else {
      // If no filters applied or no products match the filter, revert to initial product list
      initialProd();
      setisFilter(false);
      setitem(0); // Reset 'item' count to the initial value
      setfiltering(false);
    }
    setModalVisible(false);
  };

  useEffect(() => {
    if (filtering) {
      setfiltering(false);
    }
  }, [filtering]);

  // ... other parts of your code

  return (
    <ScrollView
      style={styles.tabCon}
      ref={scrollViewRef}
      onScroll={handleScroll}
    >
      <View style={styles.actions}>
        {/* <Checkbox value={all} onValueChange={() => setall((prev) => !prev)} /> */}
        <TouchableOpacity>
          {/* <FontAwesomeIcon icon={faFilter} color={"#888888"} size={25} /> */}
        </TouchableOpacity>

        <TouchableOpacity
          onPress={() => {
            setModalVisible(!modalVisible);
          }}
          style={{ flexDirection: "row" }}
        >
          <FontAwesomeIcon icon={faFilter} color={"#888888"} size={25} />
          <Text style={{ flexDirection: "row", paddingLeft: 10 }}>Filter</Text>
        </TouchableOpacity>
      </View>
      {product ? (
        <>
          {product?.length > 0 ? (
            <MasonryList
              data={prod ?? []}
              keyExtractor={(item) => item._id}
              style={styles.list}
              numColumns={2}
              showsVerticalScrollIndicator={false}
              renderItem={({ item, i }) => (
                <ProductCard
                  // like={likeClick}
                  // liked={prodLike}
                  productAll={productAll}
                  index={i}
                  product={item.product}
                  vendor={item.vendor}

                  // all={all}
                />
              )}
              containerStyle={styles.container1}
              contentContainerStyle={styles.content}
              onEndReachedThreshold={0.1}
            />
          ) : (
            <View style={{ height: "80%", alignItems: "center" }}>
              <Text>No results found</Text>
            </View>
          )}
        </>
      ) : (
        <View style={{ height: "80%", alignItems: "center" }}>
          <Text>Search a product</Text>
        </View>
      )}
      {/* <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItem}
      /> */}
      <Modal
        // animationType="slide"
        animationIn={"slideInRight"}
        // transparent={true}
        isVisible={modalVisible}
        onSwipeComplete={() => setModalVisible(false)}
        swipeDirection={["right"]}
        swipeThreshold="100"
        backdropOpacity={0.2}
        style={{ margin: 0 }}
        // propagateSwipe={true}
        deviceWidth={deviceWidth}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.Modal}>
          <View style={styles.rightModal}>
            {/* <Text>Searchingggg.........</Text> */}
          </View>
          <View style={styles.leftModal}>
            <Text style={{ fontWeight: "500", fontSize: 18 }}>
              Search Filter
            </Text>

            <View style={styles.pricefilter}>
              <Text style={styles.inputFilterTextHead}>Price:</Text>

              <View style={styles.pricefilterWrap}>
                <View style={styles.pricefilterInput}>
                  <Text style={styles.inputFilterText}>Min:</Text>
                  <TextInput
                    style={styles.inputFilterTextInput}
                    onChangeText={(e) => {
                      setmin(e);
                      // min !== "" || min !== " " || min !== null
                      //   ? setfilterStart(false)
                      //   : setfilterStart(true);
                    }}
                    value={min}
                    placeholder=""
                    keyboardType="numeric"
                  />
                </View>
                <View style={styles.pricefilterInput}>
                  <Text style={styles.inputFilterText}>Max:</Text>
                  <TextInput
                    style={styles.inputFilterTextInput}
                    onChangeText={(e) => {
                      setmax(e);
                      // max !== "" || max !== " " || max !== null
                      //   ? setfilterStart(false)
                      //   : setfilterStart(true);
                    }}
                    value={max}
                    placeholder=""
                    keyboardType="numeric"
                    // secureTextEntry={true}
                  />
                </View>
              </View>
            </View>
            <View style={styles.footerModal}>
              <TouchableOpacity
                onPress={() => filterApply()}
                style={styles.footerModalBtn}
                // disabled={filterStart?false:true}
              >
                <Text style={styles.footerModalBtnTxt}>Apply</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </ScrollView>
  );
}
function Vendors({ route }) {
  const { shops, product } = route.params;
  const [prodLike, setprodLike] = useState([]);
  const [all, setall] = useState(false);

  const [shop, setshop] = useState(shops ?? []);
  const scrollViewRef = useRef(null);
  const [item, setitem] = useState(20);
  const [isEndReached, setEndReached] = useState(false);
  useEffect(() => {
    setshop(shop?.splice(1, item) ?? []);
    console.log("length " + shops?.length + " item " + item);
  }, []);
  console.log(shops);
  const [isModalVisible, setModalVisible] = useState(false);
  // console.log(product+"here is the prodductttsss----------------------------------------------------------------");
  useEffect(() => {
    if (item <= shops?.length) {
      setshop([...shop, ...shop?.slice(item, item + 10)]);
    }
  }, [item]);
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 200;

    if (isAtEnd) {
      // You've reached the end of the ScrollView
      setEndReached(true);
      console.log("end here" + item);
      if (item <= shops?.length) {
        setitem(item + 10);
      }
      // setEndReached(false);
      // console.log("item" + item);
    }
  };
  return (
    <ScrollView
      ref={scrollViewRef}
      onScroll={handleScroll}
      style={styles.tabCon}
    >
      <View style={styles.actions}></View>
      {shops ? (
        <>
          {shops.length > 0 ? (
            <MasonryList
              data={shop ?? null}
              keyExtractor={(item) => item.id}
              style={styles.list}
              numColumns={1}
              showsVerticalScrollIndicator={false}
              renderItem={({ item, i }) => (
                <ShopCard product={product} shop={item} index={i} />
              )}
              containerStyle={styles.container1}
              contentContainerStyle={styles.content}
              onEndReachedThreshold={0.1}
            />
          ) : (
            <View style={{ height: "90%" }}>
              <Text style={{ textAlign: "center" }}>No vendor found</Text>
            </View>
          )}
        </>
      ) : (
        <View style={{ height: "90%" }}>
          <Text>Searchingggg.........</Text>
        </View>
      )}
      {/* <DeleteConfirmationModal
        isVisible={isModalVisible}
        onCancel={toggleModal}
        onConfirm={deleteItem}
      /> */}
    </ScrollView>
  );
}
const SearchPage = ({ product, productAll }) => {
  const route = useRoute();

  const { cat } = route?.params?.cat ?route?.params: "";
  // console.log(prodd)
  const [unfocus, setunfocus] = useState(false);
  const [loading, setloading] = useState(false);
  const [products, setproducts] = useState([]);
  const [vendors, setvendors] = useState([]);
  const [vendorsearch, setvendorsearch] = useState([]);
  const [isloaded, setisloaded] = useState(0);
  const isFocused = useIsFocused();

  const [search, setsearch] = useState(false);

  // const products = favorite?.find((item) => item.type === "products")?.contents;
  const shops = favorite?.find((item) => item.type === "vendors")?.contents;
  useEffect(() => {
    console.log('cat '+cat)
    if (cat) {
      searchProduct(cat);
    }
  }, [cat]);

  const searchProduct = (search) => {
    setloading(true);
    search_vendor({
      searchData: search,
    })
      .then((result) => {
        // console.log(result.data);

        if (result.error) {
          setError(result.error);
          setvendorsearch(["error occured"]);
        } else {
          if (result.data?.results.length < 1 || undefined) {
            setvendorsearch([]);
          } else {
            setvendorsearch(result.data.results);
            // setisloaded(isloaded + 1);
            // console.log("vendor" + result.data.results);
          }
          // console.log("length on search vendor " + result.data?.results);
          search_product({
            searchData: search,
          })
            .then((resultProd) => {
              // console.log(resultProd.data);

              if (resultProd.error) {
                setError(resultProd.error);
                setproducts(["error occured"]);
              } else {
                if (resultProd.data?.results.length < 1 || undefined) {
                  setproducts([]);
                } else {
                  setproducts(resultProd.data);

                  // console.log("prodd" + result.data.results);
                }
                setisloaded(true);
                // console.log("length on search " + result.data?.results.length);
              }
            })
            .catch((error) => {
              // setError(error.message);
              console.log(error.message);
            })
            .finally(() => {
              // setprodIsLoading(false); // Set loading to false when done loading
            });
          // setloading(false);
        }
      })
      .catch((error) => {
        // setError(error.message);
        console.log(error.message);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };
  useEffect(() => {
    // Initialize an empty object to keep track of unique vendors
    const vendors1 = [];
    console.log(isloaded);
    // Iterate through the original array and add vendors to the array
    if (isloaded === true) {
      products?.results?.forEach((result) => {
        const vendor = result.vendor;
        const vendorId = vendor._id;

        // Check if the vendor is not already in the vendors array
        if (vendorsearch !== []) {
          if (
            !vendors1?.some((v) => v._id === vendorId) &&
            !vendorsearch?.some((v) => v._id === vendorId)
          ) {
            vendors1.push(vendor);
          }
        } else {
          if (!vendors1?.some((v) => v._id === vendorId)) {
            vendors1.push(vendor);
          }
        }
      });
      setvendors(vendors1);
      // console.log([...vendorsearch,[vendors]])
      setvendorsearch((prevVendorSearch) => [...prevVendorSearch, ...vendors1]);
      setisloaded(false);
      setloading(false);
    }
  }, [isloaded]);

  return (
    <View
      // keyboardShouldPersistTaps="always"
      resetScrollToCoords={{ x: 0, y: 0 }}
      scrollEnabled={true}
      style={styles.container}
    >
      <View style={styles.wrapper}>
        <View style={styles.header}>
          <SearchHeader
            unfocus={unfocus}
            searchProduct={searchProduct}
            cat={cat ?? null}
          />
        </View>

        {/* <View style={styles.wrapper}> */}
        {loading === true ? (
          <View style={{ height: "90%" }}>
            <Text>Searching.........</Text>
          </View>
        ) : (
          <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={{ productsU: products, productAll: productAll }}
            />
            <Tab.Screen
              name="Vendors"
              component={Vendors}
              options={{ tabBarLabel: "Vendors" }}
              initialParams={{ shops: vendorsearch, product: product }}
            />
          </Tab.Navigator>
        )}
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffffff",
    width: "100%",
    height: "100%",
  },
  header: {
    left: 0,
    right: 0,
  },
  footer: {
    bottom: 0,
    width: "100%",
  },
  wrapper: {
    // justifyContent: "center",
    // alignItems: "center",
    height: "100%",
    width: "100%",
    marginBottom: 20,
  },
  list: {
    width: "100%",
    height: "100%",

    justifyContent: "center",
    padding: 5,
  },
  container1: {
    width: "100%",
    height: "100%",
  },
  tabCon: {
    width: "100%",
    height: "100%",
  },
  actions: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
  },
  content: {
    width: "100%",
    alignItems: "center",
    height: "100%",

    justifyContent: "center",
  },
  Modal: {
    width: "100%",
    height: "100%",
    // backgroundColor: "#ffffff",
    flexDirection: "row",
    // right:0
  },
  rightModal: {
    width: "10%",
    height: "100%",
    backgroundColor: "#ffffff20",
    // right:0
  },
  leftModal: {
    width: "90%",
    height: "100%",
    backgroundColor: "#ffffff",
    right: 0,
    padding: 15,
  },
  pricefilter: {
    width: "100%",
    padding: 10,
    marginTop: 20,
    justifyContent: "center",
    borderBottomWidth: 1,
    // borderRadius:5,
    borderColor: "#d6d6d6",
    // alignItems: "center",
  },
  pricefilterWrap: {
    flexDirection: "row",
    width: "80%",
    padding: 10,
    justifyContent: "space-between",
  },
  pricefilterInput: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
  },
  inputFilterTextInput: {
    borderWidth: 1,
    borderRadius: 5,
    borderColor: "#d6d6d6",
    backgroundColor: "#fafafa",
    padding: 5,
    width: "50%",
  },
  inputFilterText: {
    paddingRight: 15,
  },
  inputFilterTextHead: {
    paddingRight: 15,
    fontWeight: "600",
  },
  footerModal: {
    position: "absolute",
    bottom: 10,
    width: "100%",

    justifyContent: "center",
    alignItems: "center",
    zIndex: 100,
  },
  footerModalBtn: {
    // width: "80%",
    borderRadius: 50,
    padding: 10,
    paddingHorizontal: 80,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#ffaa00",
  },
  footerModalBtnTxt: {
    letterSpacing: 0.5,
    textTransform: "uppercase",
    color: "#fff",
    fontWeight: "600",
    fontSize: 16,
  },
});

export default SearchPage;
// const filterApply = () => {
//   console.log("filtering");

//   const filters = {
//     minPrice: min,
//     maxPrice: max,
//   };
//   const filteredProduct = products?.results;
//   // let filteredProduct = products;

//   let filteredProducts = [];
//   // console.log(filteredProduct);

//   if (filters.minPrice !== null || filters.maxPrice !== null) {
//     const minPrice = filters.minPrice ?? 0;
//     const maxPrice = filters.maxPrice ?? 0;
//     filteredProducts = filteredProduct?.filter(
//       (product1) =>
//         parseInt(product1.product.regular_price) >= parseInt(minPrice) &&
//         parseFloat(product1.product.regular_price) <= parseInt(maxPrice)
//     );
//     console.log("filtered" + filteredProducts);

//     // setfilterProd(filteredProducts);
//     setproduct(filterProd);

//     // setfilterProd(filteredProducts);

//     setisFilter(true);
//     setfiltering(true)
//     setModalVisible(false);
//   } else {
//     setisFilter(false);
//     setModalVisible(false);
//   }

//   // if (filters.category) {
//   //   filteredProducts = filteredProducts.filter(
//   //     (product) => product.category === filters.category
//   //   );
//   // }

//   // if (filters.shipping) {
//   //   filteredProducts = filteredProducts.filter(
//   //     (product) =>
//   //       product.shipping.toLowerCase() === filters.shipping.toLowerCase()
//   //   );
//   // }

//   // Add more conditions for other types of filters if needed
// };

// useEffect(() => {
//   if (isFilter) {
//     console.log("filtering new")
//     console.log(product)
//     setprod(product ?? []);
//     // setisFilter(false)
//     setfiltering(false)

//   } else {
//     setproduct(products);
//     setfiltering(false)

//   }
// }, [filtering]);
