import {
  faAngleDown,
  faArrowLeft,
  faPlus,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation, useRoute } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import {
  get_barangays,
  get_cities,
  get_manila_cities,
  get_provinces,
} from "../../services/addressApi/address";
import SelectDropdown from "react-native-select-dropdown";
import { update_customer } from "../../services/api/controllers/customers";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";

const AddressCheckout = () => {
  const navigation = useNavigation();
  const [unit, setunit] = useState("");

  const [street, setstreet] = useState("");
  const [fName, setfName] = useState("");
  const [lName, setlName] = useState("");
  const [company, setcompany] = useState("");
  const [email, setemail] = useState("");
  const [phone, setphone] = useState("");

  const [province, setprovince] = useState("");
  const [provinceName, setprovinceName] = useState("");
  const [provinceSelected, setprovinceSelected] = useState("");

  const [city, setcity] = useState("");
  const [cityName, setcityName] = useState("");
  const [citySelected, setcitySelected] = useState("");

  const [brgy, setbrgy] = useState("");
  const [brgyName, setbrgyName] = useState("");
  const [brgySelected, setbrgySelected] = useState("");
  const toast = useToast();

  const [zip, setzip] = useState("");
  const [landmark, setlandmark] = useState("");
  const [error, seterror] = useState("");
  const route = useRoute();

  const { product, shipMethod, payMethod, orderId, address, isrefresh } =
    route.params;
  console.log("address " + address?.length);
  const [user, setuser] = useState([]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        console.log(pass);
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  useEffect(() => {
    get_provinces()
      .then((result) => {
        if (result.status == 200) {
          setprovince([
            ...result.data,
            {
              code: "130000000",
              name: "Metro Manila",
              regionName: "National Capital Region",
              islandGroupCode: "luzon",
              psgc10DigitCode: "1300000000",
            },
          ]);
          //   console.log(result.data);
        } else {
          seterror(result.message);
          //   console.log("login error" + result);
        }
      })
      .catch((err) => {
        seterror(err);

        console.log(err);
        console.log(err + "failed to login");
      });
  }, []);
  useEffect(() => {
    if (provinceName === "Metro Manila") {
      get_manila_cities({
        id: provinceSelected,
      })
        .then((result) => {
          if (result.status == 200) {
            setcity(result.data);
            // console.log(result.data);
          } else {
            seterror(result.message);
            // console.log("login error" + result);
          }
        })
        .catch((err) => {
          seterror(err);

          console.log(err);
          console.log(err + "failed to login");
        });
    } else {
      get_cities({
        id: provinceSelected,
      })
        .then((result) => {
          if (result.status == 200) {
            setcity(result.data);
            // console.log(result.data);
          } else {
            seterror(result.message);
            // console.log("login error" + result);
          }
        })
        .catch((err) => {
          seterror(err);

          console.log(err);
          console.log(err + "failed to login");
        });
    }
  }, [provinceSelected]);
  useEffect(() => {
    get_barangays({ id: citySelected })
      .then((result) => {
        if (result.status == 200) {
          setbrgy(result.data);
          //   console.log(result.data);
        } else {
          seterror(result.message);
          //   console.log("login error" + result);
        }
      })
      .catch((err) => {
        seterror(err);

        console.log(err);
        console.log(err + "failed to login");
      });
  }, [citySelected]);
  console.log("addresss " + isrefresh);
  const AddAddress = () => {
    if ((!fName, !lName, !phone, !street, !cityName, !provinceName)) {
      toast.show("Please fill in the required fields!", {
        type: "danger",
        placement: "top",
        duration: 2000,
        offset: 30,
        animationType: "slide-in",
      });
    } else {
      if (address?.length > 0 && address !== undefined && address !== []) {
        const add = address;
        const newItem = {
          first_name: fName,
          last_name: lName,
          company: company,
          email: email,
          phone: phone,
          address_1: unit,
          address_2: street,
          city: cityName,
          province: provinceName,
          barangay: brgyName,
          country: "PH",
          billing: false,
          shipping: false,
        };
        add.push(newItem);
        update_customer({
          id: user[0]._id,
          body: {
            address: add,
          },
        })
          .then((result) => {
            // console.log(result.data);
            // navigation.navigate("Address", {
            //   isrefresh: isrefresh === true ? false : true,
            // });
            navigation.goBack();
            if (result.error) {
              seterror(result.error);
            } else {
              // setaddreses(result.data.address_book);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      } else {
        update_customer({
          id: user[0]._id,
          body: {
            address: {
              first_name: fName,
              last_name: lName,
              company: company,
              email: email,
              phone: phone,
              address_1: unit,
              address_2: street,
              city: cityName,
              province: provinceName,
              barangay: brgyName,
              country: "PH",
              billing: true,
              shipping: true,
            },
          },
        })
          .then((result) => {
            // console.log(result.data);

            if (result.error) {
              seterror(result.error);
            } else {
              // setaddreses(result.data.addreses);
              // navigation.navigate("Address", {
              //   isrefresh: isrefresh === true ? false : true,
              // });
              navigation.goBack();

              console.log(result.data);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      }
    }
  };
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => navigation.goBack()}
          style={styles.backIcon}
        >
          <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
        </TouchableOpacity>
        <Text style={styles.headerText}>My Address</Text>
      </View>

      <ScrollView style={styles.wrapper}>
        {/* <Text style={styles.text}>Content</Text> */}
        <View style={styles.wrap}>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>
              First Name:
              <Text style={{ color: "red", fontWeight: "600" }}>*</Text>
            </Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setfName(e);
              }}
              value={fName}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>
              Last Name:
              <Text style={{ color: "red", fontWeight: "600" }}>*</Text>
            </Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setlName(e);
              }}
              value={lName}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Company: (optional)</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setcompany(e);
              }}
              value={company}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>
              Phone Number:
              <Text style={{ color: "red", fontWeight: "600" }}>*</Text>
            </Text>
            <View style={styles.inputNum}>
              {/* <Text>+63 </Text> */}
              <TextInput
                style={styles.numInput}
                onChangeText={(e) => {
                  setphone(e);
                }}
                value={phone}
                // placeholder="9*********"
                // keyboardType="numeric"
                // secureTextEntry={true}
              />
            </View>
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Email:(optional)</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setemail(e);
              }}
              value={email}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Unit/Floor No.:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setunit(e);
              }}
              value={unit}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>
              Street Address:
              <Text style={{ color: "red", fontWeight: "600" }}>*</Text>
            </Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setstreet(e);
              }}
              value={street}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Province/Region:</Text>
            <SelectDropdown
              data={province}
              search={true}
              defaultButtonText="Select Province"
              renderDropdownIcon={() => <FontAwesomeIcon icon={faAngleDown} />}
              searchPlaceHolder="search"
              buttonStyle={styles.input}
              buttonTextStyle={{ fontSize: 13 }}
              onSelect={(selectedItem, index) => {
                console.log(selectedItem, index);
                setprovinceName(selectedItem.name);
                setprovinceSelected(selectedItem.code);
              }}
              buttonTextAfterSelection={(selectedItem, index) => {
                return selectedItem.name;
              }}
              rowTextForSelection={(item, index) => {
                return item.name;
              }}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>
              City/Municipality:
              <Text style={{ color: "red", fontWeight: "600" }}>*</Text>
            </Text>
            <SelectDropdown
              data={city}
              search={true}
              defaultButtonText="Select City/Municipality"
              renderDropdownIcon={() => <FontAwesomeIcon icon={faAngleDown} />}
              searchPlaceHolder="search"
              buttonStyle={styles.input}
              buttonTextStyle={{ fontSize: 13 }}
              onSelect={(selectedItem, index) => {
                console.log(selectedItem, index);
                setcityName(selectedItem.name);
                setcitySelected(selectedItem.code);
              }}
              buttonTextAfterSelection={(selectedItem, index) => {
                return selectedItem.name;
              }}
              rowTextForSelection={(item, index) => {
                return item.name;
              }}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Barangay:</Text>
            <SelectDropdown
              data={brgy}
              search={true}
              defaultButtonText="Select Barangay"
              renderDropdownIcon={() => <FontAwesomeIcon icon={faAngleDown} />}
              searchPlaceHolder="search"
              buttonStyle={styles.input}
              buttonTextStyle={{ fontSize: 13 }}
              onSelect={(selectedItem, index) => {
                console.log(selectedItem, index);
                setbrgyName(selectedItem.name);
                setbrgySelected(selectedItem.code);
              }}
              buttonTextAfterSelection={(selectedItem, index) => {
                return selectedItem.name;
              }}
              rowTextForSelection={(item, index) => {
                return item.name;
              }}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Zip Code:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setzip(e);
              }}
              value={zip}
              placeholder=""
              keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
          <View style={styles.wrapMiddleFormInput}>
            <Text style={styles.inputText}>Landmark:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(e) => {
                setlandmark(e);
              }}
              value={landmark}
              placeholder=""
              // keyboardType="numeric"
              // secureTextEntry={true}
            />
          </View>
        </View>
      </ScrollView>
      <View style={styles.footer}>
        <TouchableOpacity style={styles.footerBtn} onPress={() => AddAddress()}>
          <Text style={styles.footerBtnText}>Save</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffff",
    width: "100%",
    height: "100%",
  },
  wrapper: {
    height: "100%",
    width: "100%",
    marginBottom: 60,
  },
  wrap: {
    height: "100%",
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 30,
  },
  header: {
    alignItems: "center",
    width: "100%",
    top: 0,
    paddingLeft: 15,
    flexDirection: "row",
    borderColor: "#ddd",
    paddingBottom: 15,
    borderBottomWidth: 1,
  },
  headerText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 25,
  },
  wrapMiddleFormInput: {
    marginVertical: 6,
  },
  input: {
    height: 50,
    width: 300,
    margin: 5,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
    backgroundColor: "#fff",
  },
  inputNum: {
    height: 50,
    width: 300,
    margin: 5,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
    flexDirection: "row",
    // justifyContent: "center",9
    alignItems: "center",
    backgroundColor: "#fff",
  },
  inputText: {
    marginLeft: 15,
    fontSize: 13,
  },
  footer: {
    position: "absolute",
    bottom: 0,
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 10,
  },
  footerBtn: {
    backgroundColor: "#ff5e00",
    width: "90%",
    paddingVertical: 10,
    justifyContent: "center",
    borderRadius: 20,
    alignItems: "center",
    flexDirection: "row",
  },
  footerBtnText: {
    color: "#fff",
    fontSize: 16,
    marginRight: 10,
  },
  selectBtnText: {
    color: "#929292",
    fontSize: 15,
    marginRight: 10,
    letterSpacing: 0.6,
  },
});

export default AddressCheckout;
