import Button from "@/components/ui/Button";
import ImageLoader from "@/components/ui/ImageLoader";
import { getQueryClient } from "@/configs/query-client";
import { useCurrency } from "@/hooks/useCurrency";
import { usePaymentHandler } from "@/hooks/usePaymentHandler";
import {
  AmazonPayParams,
  BrainTreeConfigTypes,
  DepositFormType,
  StripeConfigTypes,
} from "@/types/payment";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import {
  CaretLeftIcon,
  CaretRightIcon,
  CheckIcon,
  XIcon,
} from "phosphor-react-native";
import { useCallback, useMemo, useRef, useState } from "react";
import {
  ActivityIndicator,
  Modal,
  Pressable,
  ScrollView,
  Text,
  TextInput,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import WebView from "react-native-webview";
import Stripe from "./Stripe";

export default function PaymentPage() {
  const webviewRef = useRef<WebView>(null);
  const { currency } = useCurrency();

  const [selectPaymentMethodModal, setSelectPaymentMethodModal] =
    useState(false);
  const [selectCurrencyModal, setSelectCurrencyModal] = useState(false);
  const [currencies, setCurrencies] = useState<string[] | null>(null);
  const [showCheckoutModal, setShowCheckoutModal] = useState<boolean>(false);
  const [depositForm, setDepositForm] = useState<DepositFormType | null>(null);
  const [paymentConfig, setPaymentConfig] = useState<{
    stripe: StripeConfigTypes | null;
    braintree: BrainTreeConfigTypes | null;
    amazon: AmazonPayParams | null;
  }>({
    stripe: null,
    braintree: null,
    amazon: null,
  });

  const {
    paymentGateways,
    tran,
    validationError,
    forms,
    onSubmit,
    setManualGatewayForm,
    showRedirectUrlModal,
    setShowRedirectUrlModal,
    redirectUrl,
  } = usePaymentHandler({
    depositForm,
    setShowCheckoutModal,
    setPaymentConfig,
  });

  const handleSelectDepositForm = (depositForm: DepositFormType) => {
    setCurrencies(depositForm?.supported_currencies);
    setDepositForm((prevData) => ({
      ...prevData,
      ...depositForm,
    }));
    // Set manual gateway dynamic fields as initial value
    if (depositForm?.type === "manual" && depositForm?.meta?.length) {
      const fields = depositForm?.meta?.map((field) => ({
        value: null,
        type: field?.field_type,
        label: field?.label,
      }));

      setManualGatewayForm((prev) => ({
        ...prev,
        fields,
      }));
    }
  };

  const inputPlaceholder = useMemo(() => {
    if (depositForm?.min && depositForm?.max) {
      return `Min ${currency?.symbol}${depositForm?.min} - Max ${
        currency?.symbol
      }${depositForm?.max}`;
    }
    return tran("Enter Amount");
  }, [depositForm, currency, tran]);

  const inputNumberArray = useMemo(() => {
    if (depositForm?.min && depositForm?.max) {
      return Array.from({ length: 6 }, (_, i) =>
        Number((i + 1) * depositForm?.min),
      );
    }
    return ["5", "10", "15", "20", "50", "100"];
  }, [depositForm]);

  const handleSelectCurrency = useCallback(
    (item: string) => {
      setDepositForm((prevData) => ({
        ...(prevData as DepositFormType),
        currency: item,
      }));
    },
    [setDepositForm],
  );

  console.log(depositForm, "Deposit form");

  return (
    <SafeAreaView className="bg-white h-full">
      <ScrollView>
        <View className="px-4">
          <View className="flex-row justify-between items-center py-4">
            <Pressable
              onPress={() => router.back()}
              className="size-11 justify-center items-center rounded-full border border-slate-100"
              // style={{ backgroundColor: primary[80] }}
            >
              <CaretLeftIcon size={20} weight="bold" color="#1e293b" />
            </Pressable>
          </View>
          {!showCheckoutModal ? (
            <View>
              <Text className="heading-2 text-slate-800">
                {tran("Select Payment")}
              </Text>
              <Text className=" font-satoshi-medium text-xl text-slate-500 pt-1">
                {tran("Select your preferred payment method below")}
              </Text>

              <View className="py-6">
                <Pressable
                  onPress={() => setSelectPaymentMethodModal(true)}
                  className="px-4 py-4 border border-slate-100 rounded-xl flex-row justify-between items-center"
                >
                  <Text className="text-slate-700">
                    {depositForm?.name
                      ? depositForm?.name
                      : tran("Select Payment")}
                  </Text>
                  <CaretRightIcon size={16} />
                </Pressable>
              </View>

              <View>
                {validationError?.gateway && (
                  <Text className="text-red-500">
                    {validationError.gateway}
                  </Text>
                )}

                <View>
                  <Text className="pt-6 text-xl font-semibold">
                    {tran("Enter Amount")}
                  </Text>
                  <View className="flex-row flex-wrap items-center justify-between gap-3 pb-3">
                    <Text className="text-light4">
                      If you enter {currency?.symbol}
                      {depositForm?.amount} you will get
                    </Text>
                    <View>
                      <Text>{tran("1 USD = ")}</Text>
                    </View>
                  </View>
                  <View className="border-slate-200 flex-row h-12 w-full items-center justify-start gap-2 rounded-xl border bg-transparent px-4 text-lg font-medium outline-none">
                    <Text>{currency?.symbol}</Text>
                    <TextInput
                      keyboardType="numeric"
                      value={String(depositForm?.amount || "")}
                      onChangeText={(value) => {
                        // Allow only digits
                        if (/^\d*$/.test(value)) {
                          setDepositForm(
                            (prev) =>
                              ({
                                ...(prev ?? {}), // use empty object if prev is null
                                amount: value ? Number(value) : 0,
                              }) as DepositFormType,
                          );
                        }
                      }}
                      placeholder={inputPlaceholder}
                      style={{
                        width: "100%",
                        borderWidth: 0,
                        backgroundColor: "transparent",
                      }}
                      placeholderTextColor="#999"
                      className={``}
                    />
                  </View>
                  <View className="flex-row items-center justify-start gap-2 pt-3 sm:gap-3">
                    {inputNumberArray.map((item) => (
                      <Pressable
                        key={item}
                        onPress={() =>
                          setDepositForm({
                            ...(depositForm as DepositFormType),
                            amount: Number(item),
                          })
                        }
                        className="border-slate-200  flex size-12 cursor-pointer items-center justify-center rounded-xl border  "
                      >
                        <Text className="text-slate-800 font-medium">
                          {currency?.symbol}
                          {item}
                        </Text>
                      </Pressable>
                    ))}
                  </View>
                  {validationError?.amount && (
                    <Text className="text-red-500">
                      {validationError?.amount}
                    </Text>
                  )}
                </View>

                <View>
                  <Text className="pt-6 text-xl font-semibold">
                    {tran("Select Currency")}
                  </Text>
                  <View className=" py-3">
                    <Pressable
                      onPress={() => setSelectCurrencyModal(true)}
                      className="px-4 py-4 border border-slate-100 rounded-xl flex-row justify-between items-center"
                    >
                      <Text className="text-slate-700">
                        {depositForm?.currency
                          ? depositForm?.currency
                          : tran("Select Currency")}
                      </Text>
                      <CaretRightIcon size={16} />
                    </Pressable>
                  </View>
                </View>
              </View>

              <View className="pt-12">
                <Button
                  onPress={onSubmit}
                  className="max-[400px]:w-full"
                  text="Confirm & Add Coins"
                />
              </View>
            </View>
          ) : null}

          {showCheckoutModal &&
            paymentConfig.stripe &&
            depositForm?.slug === "stripe" && (
              <Stripe
                config={paymentConfig.stripe}
                setShowCheckoutModal={setShowCheckoutModal}
              />
            )}

          {depositForm?.slug && redirectUrl && (
            <Modal animationType="fade" visible={showRedirectUrlModal}>
              <View className="pt-12">
                <Pressable onPress={() => setShowRedirectUrlModal(false)} hitSlop={10}>
                  <View pointerEvents="none">
                    <XIcon />
                  </View>
                </Pressable>
              </View>
              <WebView
                ref={webviewRef}
                originWhitelist={["*"]}
                source={{ uri: redirectUrl }}
                onNavigationStateChange={(navState) => {
                  const url = navState.url;

                  console.log(redirectUrl, url);

                  // Check if URL contains status=success
                  if (url.includes("status=success")) {
                    setShowCheckoutModal(false); // Close checkout modal if needed
                    // Close current webview modal
                    setDepositForm(null);

                    setShowRedirectUrlModal(false);

                    // Navigate to success screen
                    router.replace("/payment/Checkout?status=success");
                    // Or router.push depending on your flow
                    getQueryClient().invalidateQueries({
                      queryKey: ["deposits"],
                    });
                  }

                  if (url.includes("status=cancel")) {
                    setShowCheckoutModal(false);
                    setDepositForm(null);
                    router.replace("/payment/Checkout?status=cancel");
                  }
                  if (url.includes("status=failed")) {
                    setShowCheckoutModal(false);
                    setDepositForm(null);
                    router.replace("/payment/Checkout?status=failed");
                  }
                }}
                startInLoadingState
                renderLoading={() => (
                  <ActivityIndicator size="large" style={{ flex: 1 }} />
                )}
              />
            </Modal>
          )}

          {depositForm?.type === "manual" && (
            <View className="space-y-4 pt-6 pb-20">
              {forms.map((form: any, index: number) => (
                <View key={form.label}>
                  {form.field}
                  {validationError?.[`fields.${index}.value`] && (
                    <Text className="pt-1 text-red-500">
                      {validationError?.[`fields.${index}.value`]}
                    </Text>
                  )}
                </View>
              ))}
            </View>
          )}
        </View>

        <Modal
          animationType="fade"
          transparent={true}
          visible={selectPaymentMethodModal}
          onRequestClose={() => {
            setSelectPaymentMethodModal(!selectPaymentMethodModal);
          }}
        >
          <View className="flex-1 justify-center items-center bg-black/50">
            <View className="bg-white rounded-xl p-4 w-[90%] max-h-[70%]">
              <View className="flex-row justify-between items-center mb-4">
                <Text className="text-lg font-semibold">
                  Select Payment Method
                </Text>
                <Pressable onPress={() => setSelectPaymentMethodModal(false)}>
                  <Ionicons name="close" size={24} color="black" />
                </Pressable>
              </View>
              <ScrollView showsVerticalScrollIndicator={false}>
                <View className=" gap-y-4">
                  {paymentGateways?.map((item) => (
                    <Pressable
                      key={item.id}
                      onPress={() => {
                        handleSelectDepositForm(item as DepositFormType);
                        setSelectPaymentMethodModal(false);
                      }}
                      className={`${
                        depositForm?.slug === item.slug
                          ? "border-primary"
                          : "border-slate-200"
                      } relative flex-row cursor-pointer items-center justify-start gap-2 rounded-md border px-3 py-4`}
                    >
                      <ImageLoader
                        src={item?.image}
                        className="h-8 w-8 rounded-full object-cover"
                      />
                      <Text className="text-sm font-medium">{item.name}</Text>
                      <View
                        className={`absolute top-2 right-2 flex  size-6 items-center justify-center rounded-full border ${
                          depositForm?.slug === item.slug
                            ? "border-primary bg-primary text-white"
                            : "border-slate-200 text-transparent"
                        }`}
                      >
                        <CheckIcon size={12} />
                      </View>
                    </Pressable>
                  ))}
                </View>
              </ScrollView>
            </View>
          </View>
        </Modal>
        <Modal
          animationType="fade"
          transparent={true}
          visible={selectCurrencyModal}
          onRequestClose={() => {
            setSelectCurrencyModal(!selectCurrencyModal);
          }}
        >
          <View className="flex-1 justify-center items-center bg-black/50">
            <View className="bg-white rounded-xl p-4 w-[90%] max-h-[70%]">
              <View className="flex-row justify-between items-center mb-4">
                <Text className="text-lg font-semibold">Select Currency</Text>
                <Pressable onPress={() => setSelectCurrencyModal(false)}>
                  <Ionicons name="close" size={24} color="black" />
                </Pressable>
              </View>
              <ScrollView showsVerticalScrollIndicator={false}>
                <View className=" gap-y-4">
                  {currencies?.map((item, idx) => (
                    <Pressable
                      className="hover:text-primary cursor-pointer duration-300"
                      key={idx}
                      onPress={() => {
                        handleSelectCurrency(item);
                        setSelectCurrencyModal(false);
                      }}
                    >
                      <Text> {item}</Text>
                    </Pressable>
                  ))}
                </View>
              </ScrollView>
            </View>
          </View>
        </Modal>
      </ScrollView>
    </SafeAreaView>
  );
}
