import {
  View,
  Text,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  StatusBar,
  Platform,
  Dimensions,
  Appearance,
} from "react-native";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { publicApi, userAddress } from "../../redux/actions";
import { useNavigation } from "@react-navigation/native";
import { asyncAwesomeAlert } from "../../utils/AsyncWrappers";

//components
import Navbar from "../../components/Navbar";
import CustomPressable from "../../components/Pressable";
import CustomTextInput from "../../components/CustomTextInput";
import Select from "../../components/Select";
import MapSelector from "../../components/MapSelector";

//style
import tw from "tailwind-rn";
import Colors from "../../constants/Colors";
import fontSize from "../../constants/fontSize";

const ios = Platform.OS === "ios";

const Address = ({
  city,
  province,
  getCity,
  getProvince,
  provinces,
  cities,
  createAddress,
  loading,
  setPhase,
  cityLoading,
}) => {
  const colorScheme = Appearance.getColorScheme();
  const navigation = useNavigation();

  const [addressFields, setAddressFields] = useState({});
  const [mapAddress, setMapAddress] = useState(null);

  useEffect(() => {
    getProvince();
  }, []);

  useEffect(() => {
    if (addressFields?.provinceId) {
      getCity({
        provinceId: provinces.filter(
          (province) => province.name === addressFields?.provinceId
        )[0].id,
      });
    }
  }, [addressFields]);

  const onChange = (name, value) => {
    setAddressFields({ ...addressFields, [name]: value });
  };

  const submit = () => {
    const {
      firstName,
      lastName,
      cellphone,
      phone,
      address,
      provinceId,
      cityId,
      postalCode,
    } = addressFields;

    if (!firstName) {
      return asyncAwesomeAlert("خطا", "نام خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!lastName) {
      return asyncAwesomeAlert("خطا", "نام خانوادگی خود را وارد کنید", {
        showCancelButton: false,
      });
    }
    if (!cellphone) {
      return asyncAwesomeAlert("خطا", "شماره موبایل خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!phone) {
      return asyncAwesomeAlert("خطا", "شماره تلفن خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!provinceId) {
      return asyncAwesomeAlert("خطا", "نام استان خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!cityId) {
      return asyncAwesomeAlert("خطا", "نام شهرستان خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!postalCode) {
      return asyncAwesomeAlert("خطا", "کد پستی خود را وارد کنید.", {
        showCancelButton: false,
      });
    }
    if (!mapAddress) {
      return asyncAwesomeAlert("خطا", "آدرس خود را از روی نقشه انتخاب کن", {
        showCancelButton: false,
      });
    }

    createAddress({
      firstName,
      lastName,
      cellphone,
      phone,
      address: mapAddress,
      provinceId: provinces.filter(
        (province) => province.name === provinceId
      )[0].id,
      cityId: cities.filter((city) => city.name === cityId)[0]?.id,
      postalCode,
      location: null,
    });

    navigation.goBack();
  };

  const Header = ({ title, text }) => {
    return (
      <View style={tw("flex flex-col mt-2")}>
        <Text
          style={{
            fontFamily: "bold",
            fontSize: fontSize.lg,
            color: Colors.theme1[colorScheme].gray20,
          }}
        >
          {title}
        </Text>
        <Text
          style={{
            fontFamily: "regular",
            fontSize: fontSize.sm,
            color: Colors.theme1[colorScheme].gray20 + "aa",
          }}
        >
          {text}
        </Text>
      </View>
    );
  };

  return (
    <SafeAreaView
      style={{
        paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
        position: "relative",
      }}
    >
      <Navbar
        headerOptions={{
          logo: false,
          menu: true,
          hamburgerMenu: false,
          title: "",
          bookmark: true,
          qr: false,
          back: true,
        }}
      />
      <ScrollView
        contentContainerStyle={styles.contentContainerStyle}
        style={styles.container}
      >
        <View style={tw("w-full flex flex-col pb-4")}>
          {/* <MapSelector /> */}
          <Header
            title="اطلاعات هویتی"
            text="( لطفا نام و نام خانوادگی خود را به طور کامل وارد نمایید )"
          />
          <CustomTextInput
            label="نام"
            placeholder=""
            textAlign="right"
            name="firstName"
            maxlength="40"
            value={addressFields?.firstName}
            onChange={(name, value) => onChange(name, value)}
            autoFocus={false}
            regex={(val) => val}
          />
          <CustomTextInput
            label="نام خانوادگی"
            placeholder=""
            textAlign="right"
            name="lastName"
            maxlength="60"
            value={addressFields?.lastName}
            onChange={(name, value) => onChange(name, value)}
            autoFocus={false}
            regex={(val) => val}
          />
          <Header
            title="شماره تماس"
            text="( شماره موبایل و شماره تلفن ثابت خود را 
            به همراه پیش شماره وارد کنید )"
          />
          <CustomTextInput
            label="شماره موبایل"
            placeholder=""
            textAlign="left"
            name="cellphone"
            maxlength="11"
            value={addressFields?.cellphone}
            onChange={(name, value) => onChange(name, value)}
            autoFocus={false}
            regex={(val) => val}
          />
          <CustomTextInput
            label="شماره تلفن"
            placeholder=""
            textAlign="left"
            name="phone"
            maxlength="11"
            value={addressFields?.phone}
            onChange={(name, value) => onChange(name, value)}
            autoFocus={false}
            regex={(val) => val}
          />
          <Header
            title="آدرس"
            text="( لطفا نام استان و شهرستان و آدرس
            خود را با دقت تکمیل نمایید )"
          />
          <View style={tw("w-full mt-4")}>
            <Select
              defaultValue={province[0]}
              onChange={(name, value) => onChange(name, value)}
              options={province}
              width={"100%"}
              name="provinceId"
            />
          </View>
          <View style={tw("w-full mt-4")}>
            <Select
              defaultValue={city[0]}
              onChange={(name, value) => onChange(name, value)}
              options={city}
              width={"100%"}
              name="cityId"
            />
          </View>
          <View style={tw('mb-4')}>
            <CustomTextInput
              label="کد پستی"
              placeholder=""
              textAlign="left"
              name="postalCode"
              maxlength="60"
              value={addressFields?.postalCode}
              onChange={(name, value) => onChange(name, value)}
              autoFocus={false}
              regex={(val) => val}
            />
          </View>

          <CustomPressable
            title={"ثبت آدرس"}
            backgroundColor={Colors.theme1[colorScheme].greenCF}
            color={"white"}
            border={{ color: "#196EC0", width: 0 }}
            width={"100%"}
            onPress={() => navigation.push("Address")}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  contentContainerStyle: {
    paddingBottom: 100,
  },
  container: {
    width: Dimensions.get("window").width,
    backgroundColor: "white",
    flexDirection: "column",
    paddingVertical: 5,
    paddingHorizontal: 16,
  },
});

const mapStateToProps = (state) => ({
  provinces: state.publicApi.provinces,
  province: state.publicApi.province,
  cities: state.publicApi.cities,
  city: state.publicApi.city,
  loading: state.userAddress.loading,
  cityLoading: state.publicApi.loading,
});

const mapDispatchToProps = {
  getProvince: publicApi.getProvince,
  getCity: publicApi.getCity,
  createAddress: userAddress.add,
};

export default connect(mapStateToProps, mapDispatchToProps)(Address);