import React, { useEffect, useState } from "react";
import { TextInput, View, Text, TouchableOpacity } from "react-native";
import { commonStyles } from "../../../../../styles/commonStyle";
import { external } from "../../../../../styles/externalStyle";
import { appColors, fontSizes, windowWidth } from "@src/themes";
import styles from "../../styles";
import { useValues } from "@src/utils/context/index";
import { useSelector } from "react-redux";
import CountryPicker, {
  getAllCountries,
} from "react-native-country-picker-modal";
import { CountryCodeContainerProps } from "./types";

export function CountryCodeContainer({
  setCca2,
  setCountryCode,
  phoneNumber,
  setPhoneNumber,
  width,
  borderColor,
  smsGateway,
  countryCode,
  error,
  setError,
  style,
  parcel,
}: CountryCodeContainerProps) {
  const { viewRTLStyle, isDark, textRTLStyle, bgFullStyle } = useValues();
  const { translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting
  );
  const [country, setCountry] = useState({
    callingCode: [
      `${taxidoSettingData?.cabbooking_values?.ride?.country_code || ""}`,
    ],
    cca2: "",
    emoji: "",
  });
  const [numberShow, setNumberShow] = useState<boolean>(true);
  const [visible, setVisible] = useState<boolean>(false);

  useEffect(() => {
    const syncCountryFromProp = async () => {
      if (!countryCode) return;

      const codeOnly = countryCode.replace("+", "");
      const countries = await getAllCountries();
      const match: any = countries.find((c) =>
        c.callingCode.includes(codeOnly)
      );

      if (match) {
        setCountry({
          callingCode: [codeOnly],
          cca2: match.cca2,
          emoji: match.emoji,
        });
      }
    };

    syncCountryFromProp();
  }, [countryCode]);

  useEffect(() => {
    const fetchCountryFromCode = async () => {
      const code = taxidoSettingData?.cabbooking_values?.ride?.country_code;

      if (code) {
        try {
          const countries = await getAllCountries();
          const match = countries.find((c) =>
            c.callingCode.includes(code.toString())
          );

          if (match) {
            setCountry({
              callingCode: [code.toString()],
              cca2: match.cca2,
              emoji: "",
            });
          }
        } catch (err) {
          console.error("Error fetching countries:", err);
        }
      }
    };

    fetchCountryFromCode();
  }, [taxidoSettingData?.cabbooking_values?.ride?.country_code]);

  const handleTextChange = (newPhoneNumber: string) => {
    if (error) {
      setError("");
    }
    if (smsGateway === "firebase") {
      const onlyNumbers = newPhoneNumber.replace(/[^0-9]/g, "");
      setPhoneNumber(onlyNumbers);
      setNumberShow(true);
      return;
    }
    setPhoneNumber(newPhoneNumber);
    const isNumeric = /^\d*$/.test(newPhoneNumber);
    setNumberShow(isNumeric);
  };

  const onSelect = (selectedCountry: any) => {
    setCountry(selectedCountry);
    setVisible(false);
    if (setCountryCode) {
      setCountryCode(`+${selectedCountry.callingCode[0]}`);
    }
    if (setCca2) {
      setCca2(selectedCountry.cca2);
    }
  };

  return (
    <View>
      <Text
        style={[
          styles.phoneNumber,
          {
            color: isDark ? appColors.whiteColor : appColors.blackColor,
            fontSize: parcel ? fontSizes.FONT17 : fontSizes.FONT19,
            marginBottom: parcel && windowWidth(10),
            textAlign: textRTLStyle
          },
        ]}
      >
        {parcel
          ? translateData.parcelReceiverNumber
          : numberShow
            ? translateData?.phoneNumber
            : translateData?.email}
      </Text>
      <View>
        <View
          style={[
            external.fd_row,
            external.ai_center,
            external.mt_5,
            {
              flexDirection: viewRTLStyle,
              backgroundColor: bgFullStyle,
              borderColor: isDark
                ? appColors.darkBorder
                : appColors.loaderPrimary,
            },
            styles.input,
            style,
          ]}
        >
          {numberShow && (
            <TouchableOpacity
              style={[styles.countryCodeContainer]}
              onPress={() => setVisible(true)}
            >
              <View style={styles.pickerButton}>
                <CountryPicker
                  countryCode={
                    countryCode ? countryCode : country.callingCode[0]
                  }
                  withFilter={true}
                  withFlag={true}
                  withCallingCode={true}
                  withAlphaFilter={true}
                  withEmoji={true}
                  onSelect={onSelect}
                  visible={visible}
                  onClose={() => setVisible(false)}
                  withFlagButton={false}
                />
                {country.callingCode[0] && (
                  <Text
                    style={[
                      styles.codeText,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.blackColor,
                      },
                    ]}
                  >
                    {country.emoji} +{country.callingCode[0]}
                  </Text>
                )}
              </View>
            </TouchableOpacity>
          )}
          {numberShow && (
            <View
              style={[
                styles.divider,
                {
                  backgroundColor: isDark
                    ? appColors.darkBorder
                    : appColors.border,
                },
              ]}
            />
          )}
          <View
            style={[
              styles.phoneNumberInput,
              {
                width: (numberShow ? width ?? "74%" : "100%") as any,
                flexDirection: viewRTLStyle as
                  | "row"
                  | "row-reverse"
                  | "column"
                  | "column-reverse",
                borderColor: borderColor,
                right: numberShow ? 0 : 3,
              },
            ]}
          >
            <TextInput
              style={[
                [
                  commonStyles.regularText,
                  {
                    color: isDark ? appColors.whiteColor : appColors.blackColor,
                  },
                ],
                [styles.inputText, { textAlign: textRTLStyle }],
              ]}
              placeholderTextColor={
                isDark ? appColors.darkText : appColors.gray
              }
              placeholder={translateData.enterNumberandEmailBoth}
              keyboardType={
                smsGateway === "firebase"
                  ? "phone-pad"
                  : parcel
                    ? "number-pad"
                    : "email-address"
              }
              autoCapitalize="none"
              value={phoneNumber}
              onChangeText={handleTextChange}
            />
          </View>
        </View>
        {error && <Text style={styles.warningText}>{error}</Text>}
      </View>
    </View>
  );
}
