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 (
{/* setall((prev) => !prev)} /> */}
{/* */}
{
setModalVisible(!modalVisible);
}}
style={{ flexDirection: "row" }}
>
Filter
{product ? (
<>
{product?.length > 0 ? (
item._id}
style={styles.list}
numColumns={2}
showsVerticalScrollIndicator={false}
renderItem={({ item, i }) => (
)}
containerStyle={styles.container1}
contentContainerStyle={styles.content}
onEndReachedThreshold={0.1}
/>
) : (
No results found
)}
>
) : (
Search a product
)}
{/* */}
setModalVisible(false)}
swipeDirection={["right"]}
swipeThreshold="100"
backdropOpacity={0.2}
style={{ margin: 0 }}
// propagateSwipe={true}
deviceWidth={deviceWidth}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}
>
{/* Searchingggg......... */}
Search Filter
Price:
Min:
{
setmin(e);
// min !== "" || min !== " " || min !== null
// ? setfilterStart(false)
// : setfilterStart(true);
}}
value={min}
placeholder=""
keyboardType="numeric"
/>
Max:
{
setmax(e);
// max !== "" || max !== " " || max !== null
// ? setfilterStart(false)
// : setfilterStart(true);
}}
value={max}
placeholder=""
keyboardType="numeric"
// secureTextEntry={true}
/>
filterApply()}
style={styles.footerModalBtn}
// disabled={filterStart?false:true}
>
Apply
);
}
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 (
{shops ? (
<>
{shops.length > 0 ? (
item.id}
style={styles.list}
numColumns={1}
showsVerticalScrollIndicator={false}
renderItem={({ item, i }) => (
)}
containerStyle={styles.container1}
contentContainerStyle={styles.content}
onEndReachedThreshold={0.1}
/>
) : (
No vendor found
)}
>
) : (
Searchingggg.........
)}
{/* */}
);
}
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 (
{/* */}
{loading === true ? (
Searching.........
) : (
)}
);
};
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]);