import {
  View,
  Text,
  TextInput,
  FlatList,
  Image,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Keyboard,
  ScrollView,
} from "react-native";
import React, { useState } from "react";
import {
  Header,
  HeaderContainer,
  notificationHelper,
} from "@src/commonComponent";
import { commonStyles } from "@src/styles/commonStyle";
import styles from "./component/selectMethod/styles";
import { useNavigation, useTheme } from "@react-navigation/native";
import { useValues } from "@src/utils/context/index";
import { appColors, windowHeight, windowWidth } from "@src/themes";
import { Button, RadioButton } from "@src/commonComponent";
import { useDispatch, useSelector } from "react-redux";
import { walletData, walletTopUpData } from "../../api/store/actions/index";
import { WalletTopUpDatainterface } from "@src/api/interface/walletInterface";
import { CustomBackHandler } from "@src/components";
import { SkeltonAppPage } from "../bottomTab/profileTab/appPageScreen/component";
import { getValue } from "@src/utils/localstorage";
import { AppDispatch } from "@src/api/store";
import { useAppNavigation } from "@src/utils/navigation";

export function TopUpWallet() {
  const { colors } = useTheme();
  const { viewRTLStyle, isDark, bgFullLayout, textColorStyle, textRTLStyle } =
    useValues();
  const [amount, setAmount] = useState<any>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { paymentMethodData } = useSelector((state: any) => state.payment);
  const activePaymentMethods = paymentMethodData?.filter(
    (method: any) => method?.status == true
  );
  const [selectedItem, setSelectedItem] = useState<number | null>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<any>(null);
  const dispatch = useDispatch<AppDispatch>();
  const { navigate }: any = useNavigation();
  const { translateData, settingData, taxidoSettingData } = useSelector((state: any) => state.setting);
  const [topupLoading, setTopuploading] = useState(false);
  const { zoneValue } = useSelector((state: any) => state.zone);
  const { goBack } = useAppNavigation();

  console.log('settingData', settingData?.values?.activation?.demo_mode);


  const paymentData = (index: number, name: any) => {
    setSelectedItem(index === selectedItem ? null : index);
    setSelectedPaymentMethod(index === selectedItem ? null : name);
  };

  const addBalance = async () => {
    setTopuploading(true);
    const currencyCode = await getValue("selectedCurrency");
    if (amount <= 0) {
      notificationHelper("", translateData.enterAmount, "error");
      setTopuploading(false);
      return;
    }

    if (!selectedPaymentMethod) {
      notificationHelper("", translateData.paymentMethodSelect, "error");
      setTopuploading(false);
      return;
    }

    let payload: WalletTopUpDatainterface = {
      amount: amount,
      payment_method: selectedPaymentMethod,
      currency_code: "USD",
    };

    dispatch(walletTopUpData(payload))
      .unwrap()
      .then(async (res: any) => {

        if (settingData?.values?.activation?.demo_mode == '1') {
          dispatch(walletData() as any);
          notificationHelper("", translateData?.toupsucess, "success");
          goBack();
          return;
        }

        if (res?.is_redirect) {
          navigate("PaymentWebView", {
            url: res.url,
            selectedPaymentMethod: selectedPaymentMethod,
            dataValue: res,
          });
          setTopuploading(false);
        }
      })
      .catch((error) => { });
  };

  const renderItem = ({ item, index }) => (
    <TouchableOpacity
      onPress={() => {
        if (!topupLoading) paymentData(index, item?.slug);
      }}
      activeOpacity={topupLoading ? 1 : 0.7}
    >
      <View
        style={{
          flexDirection: viewRTLStyle,
          alignItems: "center",
          justifyContent: "space-between",
          paddingHorizontal: windowHeight(6),
        }}
      >
        <View
          style={[
            styles.modalPaymentView,
            {
              backgroundColor: isDark
                ? appColors.primaryText
                : appColors.whiteColor,
              flexDirection: viewRTLStyle,
            },
          ]}
        >
          <CustomBackHandler />
          <View style={{ flexDirection: viewRTLStyle, flex: 1 }}>
            <View style={styles.imageBg}>
              <Image source={{ uri: item.image }} style={styles.paymentImage} />
            </View>
            <View style={styles.mailInfo}>
              <Text style={[styles.mail, { color: textColorStyle }]}>
                {item.name}
              </Text>
            </View>
          </View>
        </View>

        <View style={[styles.payBtn, { marginLeft: 0 }]}>
          <RadioButton
            checked={index === selectedItem}
            color={isDark ? appColors.whiteColor : appColors.blackColor}
            onPress={() => {
              if (!topupLoading) paymentData(index, item?.slug);
            }}
          />
        </View>
      </View>
      {index !== activePaymentMethods.length - 1 && (
        <View
          style={{
            height: windowHeight(4),
            width: "100%",
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
            marginVertical: windowHeight(4),
          }}
        />
      )}
    </TouchableOpacity>
  );

  return (
    <View
      style={[commonStyles.flexContainer, { backgroundColor: bgFullLayout }]}
    >
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View style={{ flex: 0.9 }}>
          <HeaderContainer value={translateData.topupWallet} />
          <View
            style={[
              commonStyles.flexContainer,
              {
                marginBottom: windowHeight(19),
                marginTop: windowHeight(10),
                paddingBottom: windowHeight(130),
              },
            ]}
          >
            <View
              style={{
                backgroundColor: bgFullLayout,
                height: "100%",
              }}
            >
              <View style={[styles.mainContainer]}>
                <View
                  style={[
                    styles.container,
                    ,
                    {
                      backgroundColor: isDark
                        ? appColors.primaryText
                        : appColors.whiteColor,
                      borderColor: isDark ? appColors.darkBorder : appColors.go,
                      paddingHorizontal: windowWidth(20),
                    },
                  ]}
                >
                  <Text
                    style={[
                      styles.titleTopup,
                      { color: textColorStyle, textAlign: textRTLStyle },
                    ]}
                  >
                    {translateData.amount}
                  </Text>
                  <View
                    style={[
                      styles.inputView,
                      {
                        backgroundColor: isDark
                          ? appColors.solidBorder
                          : colors.card,
                        flexDirection: viewRTLStyle,
                        borderColor: isDark
                          ? appColors.darkBorder
                          : colors.border,
                      },
                    ]}
                  >
                    <View
                      style={{
                        height: windowHeight(20),
                        width: windowHeight(20),
                        backgroundColor: appColors.dotLight,
                        borderRadius: windowHeight(20),
                        alignItems: "center",
                        justifyContent: "center",
                        marginHorizontal: windowWidth(8),
                      }}
                    >
                      <Text
                        style={[
                          styles.icons,
                          {
                            color: isDark
                              ? appColors.solidBorder
                              : appColors.whiteColor,
                          },
                        ]}
                      >
                        {zoneValue.currency_symbol}
                      </Text>
                    </View>
                    <TextInput
                      style={[
                        styles.textinput,
                        {
                          backgroundColor: isDark
                            ? appColors.solidBorder
                            : colors.card,
                          color: isDark
                            ? appColors.whiteColor
                            : appColors.primaryText,
                        },
                      ]}
                      placeholder={translateData.amount}
                      placeholderTextColor={appColors.regularText}
                      keyboardType="numeric"
                      value={amount}
                      onChangeText={(text) => setAmount(text)}
                    />
                  </View>
                </View>
                <View style={styles.titleContainer}>
                  <Text
                    style={[
                      styles.title,
                      { color: textColorStyle, textAlign: textRTLStyle },
                    ]}
                  >
                    {translateData.selectMethod}
                  </Text>
                </View>

                <View
                  style={[
                    styles.container,
                    {
                      backgroundColor: isDark
                        ? appColors.primaryText
                        : appColors.whiteColor,
                    },
                    {
                      borderColor: isDark ? appColors.darkBorder : appColors.go,
                    },
                  ]}
                >
                  {isLoading ? (
                    Array.from({ length: 4 }).map((_, index) => (
                      <View
                        style={{
                          paddingHorizontal: windowHeight(12),
                          paddingVertical: windowHeight(10),
                          top: windowHeight(0),
                          borderBottomWidth: windowHeight(0.3),
                          marginHorizontal: windowHeight(4),
                          borderColor: colors.border,
                        }}
                      >
                        <SkeltonAppPage />
                      </View>
                    ))
                  ) : (
                    <FlatList
                      data={activePaymentMethods.filter(
                        (item) => item?.name.toLowerCase() !== "cash"
                      )}
                      renderItem={renderItem}
                      keyExtractor={(item) => item.id}
                      scrollEnabled={true}
                      showsVerticalScrollIndicator={false}
                    />
                  )}
                </View>
              </View>
            </View>
          </View>
        </View>
      </TouchableWithoutFeedback>
      <View
        style={[
          styles.payBottomView,
          ,
          {
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
          },
        ]}
      >
        <View style={styles.addBtn}>
          <Button
            loading={topupLoading}
            title={translateData.addBalance}
            onPress={addBalance}
          />
        </View>
      </View>
    </View>
  );
}
