import Button from "@/components/ui/Button";
import { getQueryClient } from "@/configs/query-client";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { showToast } from "@/utils/toast";
import { useStripe } from "@stripe/stripe-react-native";
import { router } from "expo-router";
import React, { useEffect, useState } from "react";
import { ActivityIndicator, Text, View } from "react-native";

type Props = {
  clientSecret: string;
  setShowCheckoutModal: React.Dispatch<React.SetStateAction<boolean>>;
};

const StripeCheckoutForm: React.FC<Props> = ({ clientSecret, setShowCheckoutModal }) => {
  const { tran } = useTranslations();
  const { initPaymentSheet, presentPaymentSheet } = useStripe();
  const [loading, setLoading] = useState(true);
  const user = useAuthStore((state) => state.user);

  useEffect(() => {
    const initializePaymentSheet = async () => {
      const { error } = await initPaymentSheet({
        paymentIntentClientSecret: clientSecret,
        merchantDisplayName: "Investra",
        defaultBillingDetails: {
          name: user?.full_name || "Customer",
          email: user?.email,
        },
        allowsDelayedPaymentMethods: true,
      });
      if (error) {
        showToast({ type: "error", text: error.message });
      }
      setLoading(false);
    };

    initializePaymentSheet();
  }, [clientSecret, user]);

  const openPaymentSheet = async () => {
    const { error } = await presentPaymentSheet();

    if (error) {
      if (error.code !== "Canceled") {
        showToast({ type: "error", text: error.message });
      }
    } else {
      showToast({ type: "success", text: tran("Payment successful!") });
      getQueryClient().invalidateQueries({
        queryKey: ["deposits"],
        exact: false,
      });
      setShowCheckoutModal(false);
      router.push({
        pathname: "/(screens)/payment/Checkout",
        params: { status: "success" },
      });
    }
  };

  if (loading) {
    return (
      <View className="py-10 items-center justify-center">
        <ActivityIndicator size="large" color="#000000" />
        <Text className="mt-2 font-manrope-medium text-slate-500">{tran("Initialising payment...")}</Text>
      </View>
    );
  }

  return (
    <View className="pb-6">
      <Text className="text-slate-500 font-manrope-medium mb-6">{tran("Your payment is ready to be processed securely via Stripe.")}</Text>
      <Button text={tran("Complete Payment")} onPress={openPaymentSheet} />
    </View>
  );
};

export default StripeCheckoutForm;
