import {
  faBagShopping,
  faBox,
  faCarSide,
  faCircleQuestion,
  faClock,
  faHeart,
  faI,
  faKey,
  faRankingStar,
  faTruck,
  faUserGear,
  faWallet,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Image,
  ScrollView,
  FlatList,
} from "react-native";
import MasonryList from "@react-native-seoul/masonry-list";
import Card from "../../components/profile/Card";
import { faStar } from "@fortawesome/free-solid-svg-icons";
import AsyncStorage from "@react-native-async-storage/async-storage";
import SelectDropdown from "react-native-select-dropdown";
import { get_orders_by_customer } from "../../services/api/controllers/order";
const width = Dimensions.get("window").width;

const settings = [
  {
    icon: <FontAwesomeIcon icon={faBagShopping} color={"#777777"} size={25} />,
    label: "My Purchases",
    nav: "MyPurchases",
  },
  // {
  //   icon: <FontAwesomeIcon icon={faWallet} color={"#777777"} size={25} />,
  //   label: "My Wallet",
  //   nav: "MyWallet",
  // },
  {
    icon: <FontAwesomeIcon icon={faHeart} color={"#777777"} size={25} />,
    label: "My Favorites",
    nav: "MyFavorites",
  },
  // {
  //   icon: <FontAwesomeIcon icon={faClock} color={"#777777"} size={25} />,
  //   label: "View History",
  //   nav: "ViewHistory",
  // },
  {
    icon: <FontAwesomeIcon icon={faUserGear} color={"#777777"} size={25} />,
    label: "Account Settings",
    nav: "AccountSettings",
  },
  {
    icon: (
      <FontAwesomeIcon icon={faCircleQuestion} color={"#777777"} size={25} />
    ),
    label: "Help Center",
    nav: "HelpCenter",
  },
  {
    icon: <FontAwesomeIcon icon={faKey} color={"#777777"} size={25} />,
    label: "Privacy Policy",
    nav: "Privacy",
  },
];

const Profile = ({ userLoggedin }) => {
  const navigation = useNavigation();
  const countries = ["Egypt", "Canada", "Australia", "Ireland"];
  const [user, setuser] = useState([]);
  const [purchase, setpurchase] = useState([]);
  const [error, setError] = useState(null);
  const [toShip, settoship] = useState(0);
  const [toPay, settopay] = useState(0);
  const [toReceive, settoreceived] = useState(0);
  const [completed, setcomplete] = useState(0);
  const [isLoggedin, setisLoggedin] = useState(false);

  const isFocused = useIsFocused();

  // AsyncStorage.getItem("userData")
  //   .then((pass) => {
  //     const userDataArray = JSON.parse(pass);
  //     setuser(userDataArray);
  //   })
  //   .catch((error) => {
  //     console.log(error + "weeewwww");
  //   });
  useEffect(() => {
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          setisLoggedin(true);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, [isFocused]);

  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("userData")
      .then((pass) => {
        if (pass !== null) {
          const userDataArray = JSON.parse(pass);
          setuser(userDataArray);
          get_orders_by_customer({
            id: userDataArray[0]?._id,
          })
            .then((result) => {
              console.log("result" + result.data);

              if (result.error) {
                setError(result.error);
              } else {
                setpurchase(result.data);
                //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//
                setcomplete(
                  result.data?.filter(
                    (item) =>
                      item.status === "COMPLETED" || item.status === "Completed"
                  ) ?? []
                );
                settoreceived(
                  result.data?.filter(
                    (item) =>
                      item.status === "TO RECEIVE" ||
                      item.status === "To Receive"
                  ) ?? []
                );
                settopay(
                  result.data?.filter(
                    (item) =>
                      item.status === "TO PAY" || item.status === "To Pay"
                  ) ?? []
                );
                settoship(
                  result.data?.filter(
                    (item) =>
                      item.status === "TO SHIP" || item.status === "To Ship"
                  ) ?? []
                );
                console.log(purchaseSorted);
                setload(false);
              }
            })
            .catch((error) => {
              setError(error.message);
            })
            .finally(() => {
              // setprodIsLoading(false); // Set loading to false when done loading
            });
          console.log(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    if (userLoggedin == true) {
      AsyncStorage.getItem("userData")
        .then((pass) => {
          if (pass !== null) {
            const userDataArray = JSON.parse(pass);
            setuser(userDataArray);
            get_orders_by_customer({
              id: userDataArray[0]?._id,
            })
              .then((result) => {
                console.log("result" + result.data);

                if (result.error) {
                  setError(result.error);
                } else {
                  setpurchase(result.data);
                  //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//
                  setcomplete(
                    result.data?.filter(
                      (item) =>
                        item.status === "COMPLETED" ||
                        item.status === "Completed"
                    ) ?? []
                  );
                  settoreceived(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO RECEIVE" ||
                        item.status === "To Receive"
                    ) ?? []
                  );
                  settopay(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO PAY" || item.status === "To Pay"
                    ) ?? []
                  );
                  settoship(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO SHIP" || item.status === "To Ship"
                    ) ?? []
                  );
                  console.log(purchaseSorted);
                  setload(false);
                }
              })
              .catch((error) => {
                setError(error.message);
              })
              .finally(() => {
                // setprodIsLoading(false); // Set loading to false when done loading
              });
            console.log(pass);
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
    } else if (userLoggedin == false) {
      setpurchase([]);
      setuser([]);
    }
  }, [userLoggedin]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    console.log("prof loaded" + userLoggedin);
    if (user) {
      console.log("prof loaded here");

      AsyncStorage.getItem("userData")
        .then((pass) => {
          if (pass !== null) {
            const userDataArray = JSON.parse(pass);
            setuser(userDataArray);
            get_orders_by_customer({
              id: userDataArray[0]?._id,
            })
              .then((result) => {
                console.log("result" + result.data);

                if (result.error) {
                  setError(result.error);
                } else {
                  setpurchase(result.data);
                  //---------- CREATE A CART LIST CATEGORIZED BY SHOP ANME -------------//
                  setcomplete(
                    result.data?.filter(
                      (item) =>
                        item.status === "COMPLETED" ||
                        item.status === "Completed"
                    ) ?? []
                  );
                  settoreceived(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO RECEIVE" ||
                        item.status === "To Receive"
                    ) ?? []
                  );
                  settopay(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO PAY" || item.status === "To Pay"
                    ) ?? []
                  );
                  settoship(
                    result.data?.filter(
                      (item) =>
                        item.status === "TO SHIP" || item.status === "To Ship"
                    ) ?? []
                  );
                  console.log(purchaseSorted);
                  setload(false);
                }
              })
              .catch((error) => {
                setError(error.message);
              })
              .finally(() => {
                // setprodIsLoading(false); // Set loading to false when done loading
              });
            console.log(pass);
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
    } else if (!user) {
      setpurchase([]);
      setuser([]);
    }
  }, [isFocused]);
  const shippingAddress = user[0]?.address?.find(
    (address) => address.shipping === true
  );
  // const toShip =
  //   purchase?.filter(
  //     (item) => item.status === "TO SHIP" || item.status === "To Ship"
  //   ) ?? [];
  // const toReceive =
  //   purchase?.filter(
  //     (item) => item.status === "TO RECEIVE" || item.status === "To Receive"
  //   ) ?? [];
  // const toPay =
  //   purchase?.filter(
  //     (item) => item.status === "TO PAY" || item.status === "To Pay"
  //   ) ?? [];
  // const completed =
  //   purchase?.filter(
  //     (item) => item.status === "COMPLETED" || item.status === "Completed"
  //   ) ?? [];
  console.log(user);
  return (
    <View style={styles.container}>
      <View style={styles.title}>
        <Text style={styles.titleText}>ACCOUNT</Text>
      </View>
      <View style={styles.wrapper}>
        <View style={styles.header}>
          <View style={styles.headerWrap}>
            {user.length !== 0 ? (
              <View style={styles.headerTop}>
                <Image
                  style={{
                    width: 60,
                    height: 60,
                    resizeMode: "cover",
                    borderRadius: 100,
                    marginLeft: 20,
                  }}
                  source={{
                    uri:
                      user[0]?.customer_image ??
                      "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyvLBxIU54Q3fueLL83PvG1eNSofzpwE-iwA&usqp=CAU",
                  }}
                />
                <View style={styles.headerTopLeft}>
                  <View style={styles.details}>
                    <Text style={styles.headerTopSubText}>Username: </Text>

                    <Text style={styles.headerTopText}>
                      {user[0]?.first_name} {user[0]?.last_name}
                    </Text>
                  </View>
                  <View style={styles.details}>
                    <Text style={styles.headerTopSubText}>
                      Delivery Address:
                    </Text>
                    <Text style={styles.headerTopSubTextP}>
                      {shippingAddress !== null
                        ? `${
                            shippingAddress?.address_1 +
                            " " +
                            shippingAddress?.address_2 +
                            ", " +
                            shippingAddress?.city +
                            " " +
                            shippingAddress?.province +
                            " "
                          }${
                            shippingAddress?.country === "PH"
                              ? "Philippines"
                              : shippingAddress?.country
                          }`
                        : "select address"}
                    </Text>
                  </View>
                </View>
              </View>
            ) : (
              <View style={styles.headerToplogin}>
                <TouchableOpacity
                  style={styles.loginBtn}
                  onPress={() => navigation.navigate("Login")}
                >
                  <Text style={styles.loginBtnTxt}>LOGIN</Text>
                </TouchableOpacity>
              </View>
            )}

            <View style={styles.headerBottom}>
              <View style={styles.headerBottomTitle}>
                <Text style={styles.headerBottomText}>My Orders</Text>
              </View>
              <View style={styles.headerBottomWrap}>
                <TouchableOpacity
                  style={styles.headerBottomCard}
                  disabled={isLoggedin ? false : true}
                  onPress={() => {
                    navigation.navigate("MyPurchases", { tab: "ToPay" });
                  }}
                >
                  <View style={styles.badge}>
                    <Text style={{ color: "#fff", fontSize: 10 }}>
                      {toPay?.length > 99 ? "99+" : toPay?.length ?? 0}
                    </Text>
                  </View>
                  <FontAwesomeIcon
                    icon={faWallet}
                    color={"#ffaa00"}
                    size={28}
                  />
                  <Text style={styles.headerBottomCardText}>To Pay</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.headerBottomCard}
                  disabled={isLoggedin ? false : true}
                  onPress={() => {
                    navigation.navigate("MyPurchases", { tab: "ToShip" });
                  }}
                >
                  <View style={styles.badge}>
                    <Text style={{ color: "#fff", fontSize: 10 }}>
                      {toShip?.length > 99 ? "99+" : toShip?.length ?? 0}
                    </Text>
                  </View>
                  <FontAwesomeIcon icon={faBox} color={"#ffaa00"} size={28} />
                  <Text style={styles.headerBottomCardText}>To Ship</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.headerBottomCard}
                  disabled={isLoggedin ? false : true}
                  onPress={() => {
                    navigation.navigate("MyPurchases", { tab: "ToReceive" });
                  }}
                >
                  <View style={styles.badge}>
                    <Text style={{ color: "#fff", fontSize: 10 }}>
                      {toReceive?.length > 99 ? "99+" : toReceive?.length ?? 0}
                    </Text>
                  </View>
                  <FontAwesomeIcon icon={faTruck} color={"#ffaa00"} size={28} />
                  <Text style={styles.headerBottomCardText}>To Receive</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.headerBottomCard}
                  disabled={isLoggedin ? false : true}
                  onPress={() => {
                    navigation.navigate("MyPurchases", { tab: "Completed" });
                  }}
                >
                  <View style={styles.badge}>
                    <Text style={{ color: "#fff", fontSize: 10 }}>
                      {completed?.length > 99 ? "99+" : completed?.length ?? 0}
                    </Text>
                  </View>
                  <FontAwesomeIcon icon={faStar} color={"#ffaa00"} size={28} />
                  <Text style={styles.headerBottomCardText}>To Rate</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </View>
        {/* <ScrollView style={styles.content1} > */}
        <View style={styles.content}>
          {user || user !== [] || user !== null || user !== "" ? (
            <>
              <View style={styles.headerBottomTitle}>
                <Text style={styles.contentTopText}>Settings</Text>
              </View>
              <FlatList
                data={settings}
                keyExtractor={(item) => item.label}
                style={styles.list}
                numColumns={3}
                showsVerticalScrollIndicator={false}
                renderItem={({ item, i }) => <Card key={i} cart={item} />}
                containerStyle={styles.container1}
                contentContainerStyle={styles.content}
                onEndReachedThreshold={0.1}
              />
            </>
          ) : (
            <View style={styles.headerBottomTitle}>
              <Text style={styles.contentTopText}>Settings</Text>
            </View>
          )}
        </View>
        {/* </ScrollView> */}
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    height: "100%",
    width: width,
  },
  header: {
    // position: "fixed",
    width: "100%",
    height: 260,
    justifyContent: "center",
    alignItems: "center",
    borderColor: "#f0f0f0dd",
    borderBottomWidth: 1,
    // top: 0,
  },
  title: {
    backgroundColor: "#ffaa00",
    width: "100%",
    top: 10,
    justifyContent: "center",
    padding: 10,
    paddingLeft: 20,
  },
  titleText: {
    // padding:10,
    color: "#fff",
    fontWeight: "600",
  },
  loginBtn: {
    backgroundColor: "#ffaa00",
    paddingHorizontal: 35,
    paddingVertical: 10,
  },
  loginBtnTxt: {
    color: "#fff",
    fontWeight: "600",
    letterSpacing: 0.8,
  },
  badge: {
    position: "absolute",
    top: -10,
    right: -10,
    zIndex: 20,
    height: 20,
    justifyContent: "center",
    alignItems: "center",
    width: 20,
    color: "#ff2626",
    backgroundColor: "#ff2626",
    borderRadius: 20,
  },
  headerWrap: {
    justifyContent: "center",
    alignItems: "center",
    width: "90%",
  },

  headerTop: {
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    flexDirection: "row",
  },
  headerTopText: {
    // padding:10,
    textTransform: "capitalize",
    letterSpacing: 0.7,
    color: "#2c2c2c",
    fontWeight: "600",
  },
  headerTopLeft: {
    width: "80%",
    padding: 10,
  },
  details: {
    // justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    flexDirection: "row",
  },
  headerTopSubText: {
    color: "#666666",
    fontWeight: "600",
    fontSize: 12,
  },
  headerTopSubTextP: {
    color: "#464646",
    fontWeight: "400",
    fontSize: 12,
    margin: 5,
    width: "65%",
  },
  headerBottom: {
    marginVertical: 15,
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    // flexDirection: "row",
  },
  headerBottomTitle: {
    // justifyContent: "space-between",
    // alignItems: "center",
    width: "100%",
    // flexDirection: "row",
  },
  headerBottomText: {
    // padding:10,
    color: "#333333",
    fontWeight: "600",
    fontSize: 13,
    textAlign: "left",
    marginLeft: 20,
  },
  headerBottomWrap: {
    justifyContent: "space-between",
    alignItems: "center",
    width: "70%",
    flexDirection: "row",
    marginTop: 18,
  },
  headerBottomCard: {
    justifyContent: "center",
    alignItems: "center",
  },
  headerBottomCardText: {
    color: "#5e5e5e",
    fontWeight: "400",
    fontSize: 11,
    marginTop: 5,
  },
  footer: {
    bottom: 0,
    width: "100%",
  },
  list: {
    width: "100%",
    backgroundColor: "#ffffff",
    borderColor: "#f0f0f0dd",
    borderWidth: 1,
    // justifyContent: "center",
    // alignItems: "center",
  },
  container1: {
    width: "100%",
    backgroundColor: "#ffffff",
  },
  wrapper: {
    width: "100%",
    // justifyContent: "center",
    // alignItems: "center",
    height: "100%",
  },
  content: {
    display: "flex",
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fffdf8",
  },
  content1: {
    display: "flex",
    width: "100%",
    height: "100%",
    backgroundColor: "#fffdf8",
  },
  contentTopText: {
    // padding:10,
    color: "#000000",
    fontWeight: "600",
    marginLeft: 10,
    padding: 10,
  },
  subContent: {
    width: "40%",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
    height: 60,
    borderColor: "#f0f0f0dd",
    borderWidth: 1,
  },
});

export default Profile;
