import React, { useEffect, useRef, useState } from "react";
import {
  Animated,
  Dimensions,
  LayoutAnimation,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import BottomNav from "../../components/main/BottomNav";
import Header from "../../components/main/Header";
import { get_all_vendors } from "../../services/api/controllers/vendor";
import Cart from "./Cart";
import Chat from "./Chat";
import Home from "./Home";
import Notification from "./Notification";
import Profile from "./Profile";
import { get_all_products } from "../../services/api/controllers/product";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import FontAwesome, {
  SolidIcons,
  RegularIcons,
  BrandIcons,
} from "react-native-fontawesome";
import {
  faCartShopping,
  faComments,
  faStore,
  faUserCircle,
} from "@fortawesome/free-solid-svg-icons";
import Icon from "react-native-vector-icons/FontAwesome5";
import { BottomNavigation, useTheme } from "react-native-paper";
import { FontAwesome5 } from "@expo/vector-icons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import { get_orders_by_customer } from "../../services/api/controllers/order";
import { user } from "../../constants/user";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { get_customer_login_id } from "../../services/api/controllers/customers";
import {
  get_user_token,
  user_login,
} from "../../services/api/controllers/auth";
import seedrandom from "seedrandom";

// import { user_login } from "../../services/obananapayApi/user_api";
const BottomTab = createBottomTabNavigator();
const height = Dimensions.get("window").height;
const BottomTab1 = createMaterialBottomTabNavigator();
const Main = ({ cartList, route }) => {
  const [tabActive, settabActive] = useState("home");
  // const [switchTab, setswitch] = useState("prod");
  const [switchTab, setSwitchTab] = useState("prod");
  const animatedValue = useRef(new Animated.Value(0)).current;
  const [vendors, setVendors] = useState([]);
  const [product, setproduct] = useState([]);
  const [cart, setcart] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  const [index, setIndex] = useState(0);
  const { colors } = useTheme();
  const [error, setError] = useState([]);
  const [isLoading, setIsLoading] = useState(true); // Add a loading state
  const [prodIsLoading, setprodIsLoading] = useState(true); // Add a loading state
  const navigation = useNavigation();
  const [loggedIn, setloggedIn] = useState(false);
  const [emailSaved, setemailSaved] = useState("");
  const [pass, setpass] = useState("");
  const [errors, seterror] = useState("");
  const { userLoggedin } = route.params ?? "";
  const [refresh, setrefresh] = useState(false);
  const [scrollTop, setscrollTop] = useState(false);

  const [isLoadingLayout, setIsLoadingLayout] = useState(true); // Add a loading
  const scrollViewRef = useRef(null);
  useEffect(() => {
    // Simulate a delay of 300 milliseconds
    const timer = setInterval(() => {
      setrefresh(true);
      AsyncStorage.getItem("something")
        .then((pass) => {
          if (pass) {
            // console.log("I am here sw well");

            // let emailSaved = "";
            // let pass = "";

            AsyncStorage.getItem("something")
              .then((passs) => {
                // pass = passs;
                setpass(passs);
                console.log(passs);
                AsyncStorage.getItem("email")
                  .then((emails) => {
                    setemailSaved(emails);
                    console.log(emails);
                    if (emailSaved && pass) {
                      user_login({
                        username: emailSaved.replace(/\s/g, "").toLowerCase(),
                        password: pass,
                      })
                        .then((result) => {
                          if (result.status == 200) {
                            //   setuserEmail(result.data.user.email);
                            //   settoken(result.data.token);
                            //   setuid(result.data.user._id);
                            // send_email();
                            // settoken(result.data.token);
                            // settokenHere(result.data.token);
                            console.log("I am here.... logged in");

                            AsyncStorage.setItem(
                              "AccessToken",
                              result.data.token
                            );
                            AsyncStorage.setItem(
                              "email",
                              emailSaved.replace(/\s/g, "").toLowerCase()
                            );
                            AsyncStorage.setItem("something", pass);
                            get_user_token({
                              token: result.data.token,
                            })
                              .then((results) => {
                                if (results.status == 200) {
                                  // setuid(results.data.profile.userId);
                                  AsyncStorage.setItem(
                                    "userId",
                                    results.data.profile.userId
                                  );
                                  // AsyncStorage.setItem(
                                  //   "AccessToken",
                                  //   result.data.profile.token
                                  // );
                                  console.log("I am here....");
                                  get_customer_login_id({
                                    id: results.data.profile.userId,
                                  })
                                    .then((result1) => {
                                      // console.log(result1.data);

                                      if (result1.error) {
                                        // seterror(result1.error);
                                      } else {
                                        AsyncStorage.setItem(
                                          "userData",
                                          JSON.stringify(result1.data)
                                        );
                                        AsyncStorage.getItem("userData")
                                          .then((userData) => {
                                            // setuser([userData]);
                                            const userDataArray =
                                              JSON.parse(userData);
                                            console.log(userDataArray);
                                          })
                                          .catch((error) => {
                                            console.log(error + "1weeewwww");
                                          });
                                        console.log(
                                          "I am here as well we have userrrrrr" +
                                            emailSaved +
                                            pass
                                        );
                                        // console.log(result1.data);
                                        navigation.navigate("Home");
                                      }
                                    })
                                    .catch((error) => {
                                      // setError(error.message);
                                      console.log(error.message);
                                    })
                                    .finally(() => {
                                      // setprodIsLoading(false); // Set loading to false when done loading
                                    });
                                } else {
                                  // seterror(results.message);
                                  console.log("login error" + results);
                                }
                              })
                              .catch((err) => {
                                // seterror(err);
                                console.log(err);
                                console.log(err + "failed to login");
                              });
                            //   setauth(true);
                            console.log("login success " + result.data.token);
                          } else {
                            // seterror(result.message);
                            console.log("login error" + result);
                          }
                        })
                        .catch((err) => {
                          seterror(err);
                          console.log(err);
                          console.log(err + "failed to login");
                        });
                    }
                  })
                  .catch((error) => {
                    console.log(error + "weeewwww");
                  });
              })
              .catch((error) => {
                console.log(error + "weeewwww");
              });
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
      setrefresh(!refresh);
    }, 0.97 * 60 * 60 * 1000);

    // Cleanup the timer if the component unmounts
    return () => clearInterval(timer);
  }, []);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    setrefresh(true);
    AsyncStorage.getItem("something")
      .then((pass) => {
        if (pass) {
          // console.log("I am here sw well");

          // let emailSaved = "";
          // let pass = "";

          AsyncStorage.getItem("something")
            .then((passs) => {
              // pass = passs;
              setpass(passs);
              console.log(passs);
              AsyncStorage.getItem("email")
                .then((emails) => {
                  setemailSaved(emails);
                  console.log(emails);
                  if (emailSaved && pass) {
                    user_login({
                      username: emailSaved.replace(/\s/g, "").toLowerCase(),
                      password: pass,
                    })
                      .then((result) => {
                        if (result.status == 200) {
                          //   setuserEmail(result.data.user.email);
                          //   settoken(result.data.token);
                          //   setuid(result.data.user._id);
                          // send_email();
                          // settoken(result.data.token);
                          // settokenHere(result.data.token);
                          console.log("I am here.... logged in");

                          AsyncStorage.setItem(
                            "AccessToken",
                            result.data.token
                          );
                          AsyncStorage.setItem(
                            "email",
                            emailSaved.replace(/\s/g, "").toLowerCase()
                          );
                          AsyncStorage.setItem("something", pass);
                          get_user_token({
                            token: result.data.token,
                          })
                            .then((results) => {
                              if (results.status == 200) {
                                // setuid(results.data.profile.userId);
                                AsyncStorage.setItem(
                                  "userId",
                                  results.data.profile.userId
                                );
                                // AsyncStorage.setItem(
                                //   "AccessToken",
                                //   result.data.profile.token
                                // );
                                console.log("I am here....");
                                get_customer_login_id({
                                  id: results.data.profile.userId,
                                })
                                  .then((result1) => {
                                    // console.log(result1.data);

                                    if (result1.error) {
                                      // seterror(result1.error);
                                    } else {
                                      AsyncStorage.setItem(
                                        "userData",
                                        JSON.stringify(result1.data)
                                      );
                                      AsyncStorage.getItem("userData")
                                        .then((userData) => {
                                          // setuser([userData]);
                                          const userDataArray =
                                            JSON.parse(userData);
                                          console.log(userDataArray);
                                        })
                                        .catch((error) => {
                                          console.log(error + "1weeewwww");
                                        });
                                      console.log(
                                        "I am here as well we have userrrrrr" +
                                          emailSaved +
                                          pass
                                      );
                                      // console.log(result1.data);
                                      navigation.navigate("Home");
                                    }
                                  })
                                  .catch((error) => {
                                    // setError(error.message);
                                    console.log(error.message);
                                  })
                                  .finally(() => {
                                    // setprodIsLoading(false); // Set loading to false when done loading
                                  });
                              } else {
                                // seterror(results.message);
                                console.log("login error" + results);
                              }
                            })
                            .catch((err) => {
                              // seterror(err);
                              console.log(err);
                              console.log(err + "failed to login");
                            });
                          //   setauth(true);
                          console.log("login success " + result.data.token);
                        } else {
                          // seterror(result.message);
                          console.log("login error" + result);
                        }
                      })
                      .catch((err) => {
                        seterror(err);
                        console.log(err);
                        console.log(err + "failed to login");
                      });
                  }
                })
                .catch((error) => {
                  console.log(error + "weeewwww");
                });
            })
            .catch((error) => {
              console.log(error + "weeewwww");
            });
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    setrefresh(!refresh);
  }, []);
  // console.log("vendor" + vendors[1]?._id);
  // function shuffleArray(array) {
  //   const shuffledArray = [...array];
  //   for (let i = shuffledArray.length - 1; i > 0; i--) {
  //     const j = Math.floor(Math.random() * (i + 1));
  //     [shuffledArray[i], shuffledArray[j]] = [
  //       shuffledArray[j],
  //       shuffledArray[i],
  //     ];
  //   }
  //   return shuffledArray;
  // }
  function shuffleArray(array, seed) {
    const shuffledArray = [...array];
    const rng = seedrandom(seed); // Seed the random number generator

    for (let i = shuffledArray.length - 1; i > 0; i--) {
      const j = Math.floor(rng() * (i + 1)); // Use the seeded random number generator
      [shuffledArray[i], shuffledArray[j]] = [
        shuffledArray[j],
        shuffledArray[i],
      ];
    }

    return shuffledArray;
  }
  useEffect(() => {
    // Simulate a delay of 300 milliseconds
    const timer = setTimeout(() => {
      setIsLoadingLayout(false); // Set isLoadingLayout to false after 300ms
    }, 300);

    // Cleanup the timer if the component unmounts
    return () => clearTimeout(timer);
  }, []);
  useEffect(() => {
    // Fetch vendors and update the state
    get_all_products()
      .then((result) => {
        //  console.log("result" + result);

        if (result.error) {
          setError(result.error);
        } else {
          const filtered = result.data.filter(
            (item) =>
              item.product_type !== "variation" &&
              item.product_image !== "" &&
              item.product_image !== null
          );
          setproduct(shuffleArray(filtered));
        }
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        setprodIsLoading(false); // Set loading to false when done loading
      });
    get_all_vendors()
      .then((result) => {
        // console.log("result" + result);

        if (result.error) {
          setError(result.error);
        } else {
          setVendors(shuffleArray(result.data));
        }
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        setIsLoading(false); // Set loading to false when done loading
      });
    get_orders_by_customer({
      id: user[0]._id,
    })
      .then((result) => {
        //  console.log("result" + result);

        if (result.error) {
          setError(result.error);
        } else {
          setcart(result.data);
        }
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  }, []);
  useEffect(() => {
    if (refreshing === true) {
      console.log("isssssss");
      const shufP = shuffleArray(product);
      setproduct(shufP);

      setRefreshing(false);

      // Fetch vendors and update the state
    }
  }, [refreshing]);
  return (
    <View style={styles.container} ref={scrollViewRef}>
      {/* <View style={styles.wrapper}>
        {tabActive === "home" ? (
          <Home prodIsLoading={prodIsLoading} product={product} tab={switchTab} />
        ) : tabActive === "notif" ? (
          <Notification />
        ) : tabActive === "message" ? (
          <Chat />
        ) : tabActive === "cart" ? (
          <Cart cartList={cartList} />
        ) : tabActive === "profile" ? (
          <Profile />
        ) : (
          <Home />
        )}
      </View>
      <View style={styles.footer}>
        {tabActive === "home" ? (
          <View style={styles.tabsCon}>
            <View style={styles.tabs}>
              <TouchableOpacity
                style={[
                  switchTab === "ven" ? styles.tab : styles.tabActive,

                  {
                    backgroundColor:
                      switchTab === "prod" ? backgroundColor : "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: switchTab === "prod" ? "#fff" : "#000",
                    },
                  ]}
                >
                  Products
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  switchTab === "prod" ? styles.tab : styles.tabActive,
                  {
                    backgroundColor:
                      switchTab === "ven" ? backgroundColor : "transparent",
                    transform: [
                      {
                        translateX: animatedValue.interpolate({
                          inputRange: [0, 1],
                          outputRange: [-5, 5], // Adjust the bounce distance
                        }),
                      },
                    ],
                  },
                ]}
                onPress={() => handleTabPress("ven")}
                activeOpacity={0.5}
              >
                <Text
                  style={[
                    styles.tabText,
                    {
                      color: switchTab === "ven" ? "#fff" : "#000",
                    },
                  ]}
                >
                  Vendor
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        ) : null}
        <BottomNav settabActive={settabActive} activeTab={tabActive} />
      </View> */}

      <BottomTab.Navigator
        initialRouteName="Home"
        activeColor="#ffaa00"
        inactiveColor="#b4b4b4"
        sceneAnimationType="shifting"
        style={{
          padding: 0,
          height: 10,
        }}
        screenOptions={{
          tabBarStyle: {
            backgroundColor: "#fff",
            margin: 0,
            padding: 0,
            paddingVertical: 10,
            borderWidth: 1,
            borderColor: "#e7e7e7",
            height: 60,
            // paddingBottom:-25
          },
        }}
        // shifting={true}

        // labeled={false}
      >
        <BottomTab.Screen
          name="Discover"
          // component={()=><Home prodIsLoading={prodIsLoading} product={product} tab={switchTab} />}
          options={{
            tabBarButton: (props) => {
              const isFocused = useIsFocused();
              return (
                <TouchableOpacity {...props} style={styles.botTab}>
                  {/* <TouchableOpacity
                    onPress={() => {
                      if (isFocused) {
                        console.log("scroll to top");
                        setscrollTop(true);
                      }
                    }}
                  > */}
                  <FontAwesomeIcon
                    icon={faStore}
                    color={isFocused ? "#ffaa00" : "#9c9c9c"}
                    size={25}
                    style={{
                      paddingHorizontal: 33,
                    }}
                  />
                  <Text style={{ color: isFocused ? "#ffaa00" : "#9c9c9c" }}>
                    Home
                  </Text>
                  {/* </TouchableOpacity> */}
                </TouchableOpacity>
              );
            },
            headerShown: false,
            // tabBarColor:"#fff",
          }}
        >
          {(props) => (
            <Home
              {...props}
              prodIsLoading={prodIsLoading}
              product={product ?? []}
              vendors={vendors ?? []}
              tab={switchTab}
              setRefreshing={setRefreshing}
              refreshing={refreshing}
            />
          )}
        </BottomTab.Screen>
        <BottomTab.Screen
          name="Chat"
          // component={()=><Chat prodIsLoading={prodIsLoading} product={product} tab={switchTab} />}
          options={{
            headerShown: false,
            tabBarButton: (props) => {
              const isFocused = useIsFocused();
              return (
                <TouchableOpacity {...props} style={styles.botTab}>
                  <FontAwesomeIcon
                    icon={faComments}
                    color={isFocused ? "#ffaa00" : "#9c9c9c"}
                    size={25}
                    style={{
                      paddingHorizontal: 33,
                    }}
                  />
                  <Text style={{ color: isFocused ? "#ffaa00" : "#9c9c9c" }}>
                    Chat
                  </Text>
                </TouchableOpacity>
              );
            },
          }}
        >
          {(props) => <Chat {...props} />}
        </BottomTab.Screen>
        <BottomTab.Screen
          name="Cart"
          // component={()=><Cart prodIsLoading={prodIsLoading} product={product} tab={switchTab} />}
          options={{
            headerShown: false,
            tabBarButton: (props) => {
              const isFocused = useIsFocused();
              return (
                <TouchableOpacity {...props} style={styles.botTab}>
                  <FontAwesomeIcon
                    icon={faCartShopping}
                    color={isFocused ? "#ffaa00" : "#9c9c9c"}
                    size={25}
                    style={{
                      paddingHorizontal: 33,
                    }}
                  />
                  <Text style={{ color: isFocused ? "#ffaa00" : "#9c9c9c" }}>
                    Cart
                  </Text>
                </TouchableOpacity>
              );
            },
          }}
        >
          {(props) => <Cart {...props} refresh={refresh} cartList={cart} />}
        </BottomTab.Screen>
        <BottomTab.Screen
          name="Profile"
          // component={()=><Profile prodIsLoading={prodIsLoading} product={product} tab={switchTab} />}
          options={{
            headerShown: false,
            tabBarButton: (props) => {
              const isFocused = useIsFocused();
              return (
                <TouchableOpacity {...props} style={styles.botTab}>
                  <FontAwesomeIcon
                    icon={faUserCircle}
                    color={isFocused ? "#ffaa00" : "#9c9c9c"}
                    size={25}
                    style={{
                      paddingHorizontal: 33,
                    }}
                  />
                  <Text style={{ color: isFocused ? "#ffaa00" : "#9c9c9c" }}>
                    Profile
                  </Text>
                </TouchableOpacity>
              );
            },
          }}
        >
          {(props) => <Profile userLoggedin={userLoggedin} {...props} />}
        </BottomTab.Screen>
      </BottomTab.Navigator>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffffff",
    // height: height * 0.4,
    width: "100%",
    // justifyContent: "center",
    // alignItems: "center",
    flex: 1,
  },
  header: {
    position: "fixed",
    width: "100%",
    top: 0,
  },
  footer: {
    // position: "absolute",
    bottom: 0,
    width: "100%",
  },
  wrapper: {
    height: "93%",
  },
  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",
  },
  botTab: {
    justifyContent: "center",
    alignItems: "center",
    width: "25%",
  },
});

export default Main;
