import React, { useEffect, useRef, useState, memo } from "react";
import {
  StyleSheet,
  View,
  ScrollView,
  Text,
  TouchableOpacity,
  Animated,
  RefreshControl,
} from "react-native";
import ProductList from "../../components/main/home/ProductList";
import TopCategories from "../../components/main/home/TopCategories";
import SwiperCon from "../../components/main/home/Swiper";
import Header from "../../components/main/Header";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import TopShops from "../../components/main/home/TopShops";
import ShopList from "../../components/main/home/ShopList";
import CardSkeletonLoading from "../../layout/skeleton/cardSkeleton";
import FeaturedProducts from "../../components/main/home/FeaturedProducts";
import BestDeals from "../../components/main/home/BestDeals";

const Home = ({
  product,
  prodIsLoading,
  vendors,
  scrollTop,
  refreshing,
  setRefreshing,
}) => {
  const navigation = useNavigation();
  const scrollViewRef = useRef(null);
  // const prodscrollViewRef = useRef(null);
  const [tab, setSwitchTab] = useState("prod");

  const [isLoadingLayout, setIsLoadingLayout] = useState(true);
  const [focused, setfocused] = useState(false);
  const [focused1, setfocused1] = useState(0);

  const [item, setitem] = useState(20);
  const [load, setload] = useState(false);

  const [item1, setitem1] = useState(20);

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

  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 300;

    if (isAtEnd) {
      setEndReached(true);
      console.log("end here");
      if (tab === "prod") {
        setitem(item + 15);
      } else {
        setitem1(item1 + 15);
      }
    } else {
      setEndReached(false);
    }
  };

  const isFocused = useIsFocused();
  useEffect(() => {
    if (isEndReached) {
      setload(true);
      const timer = setTimeout(() => {
        setload(false);
      }, 200);
      // Cleanup the timer if the component unmounts
      return () => clearTimeout(timer);
    }
  }, [isEndReached]);

  useEffect(() => {
    // Simulate a delay of 50 milliseconds
    setfocused(false);
    if (isLoadingLayout) {
      const timer = setTimeout(() => {
        setIsLoadingLayout(!isLoadingLayout);

        setIsLoadingLayout(false); // Set isLoadingLayout to false after 50ms

        // Set isLoadingLayout to false after 50ms
      }, 500);
      // Cleanup the timer if the component unmounts
      return () => clearTimeout(timer);
    }
  }, []);

  const animatedValue = useRef(new Animated.Value(0)).current;

  const handleTabPress = (tab) => {
    // Determine the target value based on the selected tab
    const targetValue = tab === "prod" ? 0 : 1;

    // Create a spring animation
    Animated.spring(animatedValue, {
      toValue: targetValue,
      friction: 5, // Adjust the friction to control the bounce effect
      tension: 10, // Adjust the tension to control the bounce effect
      useNativeDriver: true,
    }).start();

    // Update the selected tab
    setSwitchTab(tab);
  };
  const backgroundColor = animatedValue.interpolate({
    inputRange: [0, 1],
    outputRange: ["#ffaa00", "#ffaa00"], // Adjust colors as needed
  });

  useEffect(() => {
    setfocused(isFocused);
  }, [isFocused]);

  useEffect(() => {
    if (focused) {
      const unsubscribe = navigation.addListener("tabPress", (e) => {
        if (scrollViewRef.current) {
          scrollViewRef.current.scrollTo({
            y: 0,
            animated: true,
          });
        }
      });

      return unsubscribe;
    }
  }, [focused, navigation]);
  const onRefresh = () => {
    setRefreshing(true);
    setitem(20);
    setitem1(20);
    // Simulating refresh delay, you can replace this with your actual refresh logic
    // setTimeout(() => {
    //   setRefreshing(false);
    // }, 1000);
  };
  return (
    <View style={styles.container}>
      {/* <View > */}
      <View
        style={styles.header}
        onPress={() =>
          navigation.navigate("Search", { prodd: product ? product : null })
        }
      >
        <Header product={product ?? null} />
      </View>
      <ScrollView
        ref={scrollViewRef}
        onScroll={handleScroll}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            // Add additional props for styling or behavior if needed
          />
        }
      >
        <View style={styles.wrapper}>
          <SwiperCon />
        </View>

        {prodIsLoading ? (
          <View style={styles.skeletonCon}>
            <CardSkeletonLoading />
          </View>
        ) : (
          <>
            {tab === "prod" ? (
              <View>
                <TopCategories />
                {/* <FeaturedProducts product={product ?? []} /> */}
                {/* <BestDeals product={product ?? []} /> */}
                <ProductList
                  refreshing={refreshing}
                  product={product ?? []}
                  isEndReached={isEndReached}
                  item={item}
                />
                <Text>Load</Text>
              </View>
            ) : (
              <>
                {/* <TopShops vendors={vendors ?? []} /> */}
                <ShopList
                  product={product}
                  vendors={vendors ?? []}
                  item={item1}
                  refreshing={refreshing}
                  isEndReached={isEndReached}
                />
              </>
            )}
          </>
        )}
      </ScrollView>
      <View style={styles.tabsCon}>
        <View style={styles.tabs}>
          <TouchableOpacity
            style={[
              tab === "ven" ? styles.tab : styles.tabActive,

              {
                backgroundColor: tab === "prod" ? "#ffaa00" : "transparent",
                transform: [
                  {
                    translateX: animatedValue.interpolate({
                      inputRange: [0, 1],
                      outputRange: [-5, 5], // Adjust the bounce distance
                    }),
                  },
                ],
              },
            ]}
            onPress={() => handleTabPress("prod")}
            activeOpacity={0.5}
          >
            <Text
              style={[
                styles.tabText,
                {
                  color: tab === "prod" ? "#fff" : "#000",
                },
              ]}
            >
              Products
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              tab === "prod" ? styles.tab : styles.tabActive,
              {
                backgroundColor: tab === "ven" ? "#ffaa00" : "transparent",
                transform: [
                  {
                    translateX: animatedValue.interpolate({
                      inputRange: [0, 1],
                      outputRange: [-5, 5], // Adjust the bounce distance
                    }),
                  },
                ],
              },
            ]}
            onPress={() => {
              handleTabPress("ven");
              if (scrollViewRef.current) {
                scrollViewRef.current.scrollTo({
                  y: 0,
                  animated: true,
                });
              }
            }}
            activeOpacity={0.5}
          >
            <Text
              style={[
                styles.tabText,
                {
                  color: tab === "ven" ? "#fff" : "#000",
                },
              ]}
            >
              Vendor
            </Text>
          </TouchableOpacity>
        </View>
      </View>
      {/* </View> */}
      {load ? <Text>loading...</Text> : null}
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    width: "100%",
  },
  skeletonCon: {
    marginLeft: 5,
    justifyContent: "center",
  },
  wrapper: {
    width: "100%",
    height: 150,
    alignItems: "center",
    justifyContent: "center",
  },
  header: {
    // position: "absolute",
    width: "100%",
    top: 0,
    marginBottom: 5,
    zIndex: 20,
  },

  img: {
    width: 400,
    height: 200,
    resizeMode: "cover",
    margin: "auto",
    borderRadius: 10,
    // backgroundColor: "#ffaa00",
  },
  tabs: {
    height: 80,
    width: "100%",
    position: "absolute",
    bottom: 50,
  },
  tab: {},
  tabsCon: {
    height: 80,
    width: "100%",
    position: "absolute",
    justifyContent: "center",
    alignItems: "center",
    bottom: 15,
  },
  tabs: {
    // height: 30,
    margin: "auto",
    flexDirection: "row",
    backgroundColor: "#fff",
    borderRadius: 15,
    overflow: "hidden",
    borderWidth: 1,
    borderColor: "#ddd",
    // padding:10
  },
  tab: {
    paddingVertical: 15,
    paddingHorizontal: 25,
  },
  tabActive: {
    backgroundColor: "#ffaa00",
    paddingVertical: 15,
    paddingHorizontal: 25,
    borderRadius: 15,
  },
  tabText: {
    textTransform: "uppercase",
    color: "#383838",
    fontWeight: "600",
  },
  tabTextActive: {
    textTransform: "uppercase",
    color: "#fff",
    fontWeight: "600",
  },
});
export default Home;
// export default memo(Home);
