import React, { useState, useEffect } from "react";
import {
  TouchableWithoutFeedback,
  View,
  BackHandler,
  TouchableOpacity,
  Text,
  TextInput,
} from "react-native";
import { InputText } from "@src/commonComponent";
import { styles } from "../style";
import { useValues } from "@src/utils/context/index";
import { appColors, appFonts, windowHeight, windowWidth } from "@src/themes";
import { commonStyles } from "@src/styles/commonStyle";
import { SkeletonInput } from "./component";
import { useSelector } from "react-redux";
import {
  Country,
  CountryCode,
  getAllCountries,
} from "react-native-country-picker-modal";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useLoadingContext } from "@src/utils/loadingContext";
import { useAppNavigation } from "@src/utils/navigation";

const findCountryByCallingCode = async (code: string) => {
  const countries = await getAllCountries();
  return countries.find((country) => country.callingCode.includes(code));
};

export function DataContainer({
  data,
  width,
  setForm: setParentForm,
  phoneNumberError,
  emailError,
}: any) {
  const { isDark, viewRTLStyle, isRTL, textRTLStyle, bgContainer } =
    useValues();
  const { translateData } = useSelector((state: any) => state.setting);
  const [currentCallingCode, setCurrentCallingCode] = useState(
    data?.country_code || "+1"
  );
  const [cca2Code, setCca2Code] = useState<CountryCode | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const { addressLoaded, setAddressLoaded } = useLoadingContext();
  const [phoneNumber, setPhoneNumber] = useState(
    data?.phone ? data.phone.toString() : ""
  );
  const [form, setForm] = useState({
    username: data?.name || "",
    email: data?.email || "",
    countryCode: data?.country_code || "+1",
    cca2: cca2Code,
    phoneNumber: data?.phone ? data.phone.toString() : "",
  });

  useEffect(() => {
    setParentForm?.(form);
  }, [form, setParentForm]);

  useEffect(() => {
    if (!addressLoaded) {
      setLoading(true);
      setLoading(false);
      setAddressLoaded(true);
    }
  }, [addressLoaded, setAddressLoaded]);

  const SkeletonLoader = ({ variant }: any) => {
    let rectProps = { x: "0%", y: "0", width: "100%" };
    if (variant === 4) {
      rectProps = { x: "0%", y: "80%", width: "100%" };
    }
    return <SkeletonInput x={rectProps.x} width={rectProps.width} />;
  };

  const onChange = (name: string, value: string) => {
    setForm((prevForm) => ({ ...prevForm, [name]: value }));
  };

  const [visible, setVisible] = useState(false);

  const closeCountryPicker = () => setVisible(false);

  const handleBackgroundPress = () => closeCountryPicker();

  const handleBackPress = () => {
    if (visible) {
      setVisible(false);
      return true;
    }
    return false;
  };

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      handleBackPress
    );
    return () => backHandler.remove();
  }, [visible]);

  useEffect(() => {
    const loadCountry = async () => {
      try {
        const saved = await AsyncStorage.getItem("userCountry");
        let selected = null;
        if (saved) {
          selected = JSON.parse(saved);
        } else if (data?.country_code) {
          const rawCode = data.country_code.replace("+", "");
          const found = await findCountryByCallingCode(rawCode);
          if (found) {
            selected = {
              code: `+${found.callingCode[0]}`,
              cca2: found.cca2,
            };
          }
        }

        if (selected) {
          setCurrentCallingCode(selected.code);
          setCca2Code(selected.cca2);
          onChange("countryCode", selected.code);
          onChange("cca2", selected.cca2);
        }
      } catch (err) {}
    };
    loadCountry();
  }, [data]);

  const { navigate } = useAppNavigation();

  const gotoEdit = (field: string) => {
    navigate("EditDetails" as any, { field, form });
  };

  return (
    <View style={styles.inputContainer}>
      {loading ? (
        <View style={{ marginTop: windowHeight(20), right: windowHeight(7) }}>
          {[1, 2, 3, 4].map((variant) => (
            <View key={variant} style={{ marginBottom: windowHeight(10) }}>
              <SkeletonLoader variant={variant} />
            </View>
          ))}
        </View>
      ) : (
        <>
          <InputText
            title={translateData.userName}
            showTitle={true}
            borderColor={isDark ? bgContainer : appColors.lightGray}
            backgroundColor={
              isDark ? appColors.solidBorder : appColors.whiteColor
            }
            placeholder={translateData.enterUserName}
            placeholderTextColor={
              isDark ? appColors.darkText : appColors.regularText
            }
            value={form.username}
            onChangeText={(value) => onChange("username", value)}
          />

          <Text
            style={{
              color: isDark ? appColors.whiteColor : appColors.primaryText,
              fontFamily: appFonts.medium,
              textAlign: textRTLStyle,
              marginTop: windowHeight(8),
            }}
          >
            {translateData.mobileNumber}
          </Text>

          <View style={styles.countryMainView}>
            <View
              style={{
                flexDirection: viewRTLStyle,
                backgroundColor: isDark
                  ? appColors.solidBorder
                  : appColors.whiteColor,
                height: windowHeight(40),
                width: "100%",
                borderRadius: windowHeight(35),
                borderWidth: windowWidth(2),
                borderColor: isDark
                  ? appColors.darkBorder
                  : appColors.loaderPrimary,
              }}
            >
              <View style={[[styles.countryCodeContainer]]}>
                <TouchableOpacity
                  style={styles.pickerButton}
                  onPress={() => setVisible(true)}
                >
                  <Text
                    style={[
                      styles.codeText,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.blackColor,
                      },
                    ]}
                  >
                    {currentCallingCode}
                  </Text>
                </TouchableOpacity>
                {visible && (
                  <TouchableWithoutFeedback onPress={handleBackgroundPress}>
                    <View style={styles.touchbleView} />
                  </TouchableWithoutFeedback>
                )}
              </View>

              <View style={[styles.phoneNumberInput]}>
                <TouchableOpacity
                  onPress={() => gotoEdit("mobile")}
                  style={{ flexDirection: "row" }}
                  activeOpacity={0.7}
                >
                  <TextInput
                    style={[
                      commonStyles.regularText,
                      {
                        left: isRTL ? windowWidth(250) : windowWidth(13),
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.blackColor,
                        width: windowWidth(250),
                        borderColor: isDark
                          ? appColors.darkBorder
                          : appColors.loaderPrimary,
                      },
                    ]}
                    placeholderTextColor={
                      isDark ? appColors.darkText : appColors.regularText
                    }
                    placeholder={translateData.enterPhone}
                    keyboardType="phone-pad"
                    value={phoneNumber}
                    editable={data?.phone < 6}
                    onChangeText={(val) => {
                      if (val === "0") {
                        val = "";
                      }
                      setPhoneNumber(val);
                      onChange("phoneNumber", val);
                    }}
                  />
                </TouchableOpacity>
              </View>
            </View>
            {phoneNumberError && (
              <Text style={styles.warningText}>{phoneNumberError}</Text>
            )}
          </View>
          <TouchableOpacity>
            <InputText
              title={translateData.email}
              showTitle={true}
              borderColor={isDark ? bgContainer : appColors.lightGray}
              backgroundColor={
                isDark ? appColors.solidBorder : appColors.whiteColor
              }
              placeholder={translateData.enterEmail}
              placeholderTextColor={
                isDark ? appColors.darkText : appColors.regularText
              }
              value={form.email}
              onChangeText={(value) => onChange("email", value)}
              textOnpress={() => gotoEdit("email")}
            />
          </TouchableOpacity>
          {emailError && <Text style={styles.warningText}>{emailError}</Text>}
        </>
      )}
    </View>
  );
}
