import BackButtonTitle from "@/components/ui/BackButtonTitle";
import BottomSheet from "@/components/ui/BottomSheet";
import Button from "@/components/ui/Button";
import AppText from "@/components/ui/app-text";
import NoDataFound from "@/components/ui/no-data-found";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { useKycCheck } from "@/hooks/useKycCheck";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { CaretRightIcon, MagnifyingGlassIcon, PlusIcon, XIcon } from "phosphor-react-native";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, FlatList, Image, Keyboard, Modal, Pressable, RefreshControl, ScrollView, TextInput, View } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import WebView from "react-native-webview";
import Stripe from "../payment/Stripe";

interface Deposit {
  id: number;
  payment_identifier: string;
  method_name: string;
  amount: number;
  payable: number;
  currency: string;
  status: string;
  created_at: string;
  payment_method: {
    image: string;
    name: string;
  };
}

interface PaymentMethod {
  id: number;
  name: string;
  image: string;
  slug: string;
  min: number;
  max: number;
  fixed_charge: number;
  percent_charge: number;
  supported_currencies: string[];
}

const StatusBadge = ({ status }: { status: string }) => {
  const { success, danger, secondary } = useColor();
  const { tran } = useTranslations();

  const getStatusStyle = () => {
    switch (status.toLowerCase()) {
      case "completed":
      case "approved":
        return { bg: "bg-emerald-50", text: "text-emerald-600", dot: "bg-emerald-500", label: tran("Success") };
      case "pending":
        return { bg: "bg-amber-50", text: "text-amber-600", dot: "bg-amber-500", label: tran("Pending") };
      case "failed":
      case "rejected":
        return { bg: "bg-rose-50", text: "text-rose-600", dot: "bg-rose-500", label: tran("Failed") };
      default:
        return { bg: "bg-slate-50", text: "text-slate-600", dot: "bg-slate-400", label: status };
    }
  };

  const style = getStatusStyle();
  return (
    <View className={`flex-row items-center gap-1.5 px-3 py-1 rounded-full ${style.bg}`}>
      <View className={`w-1.5 h-1.5 rounded-full ${style.dot}`} />
      <AppText className={`text-[10px] font-manrope-bold uppercase tracking-tight ${style.text}`}>{style.label}</AppText>
    </View>
  );
};

const DepositCard = ({ item }: { item: Deposit }) => {
  const { currency } = useCurrency();
  const { translateNumber } = useTranslations();

  return (
    <View className="bg-white rounded-[28px] p-4 mb-4 border border-slate-100 shadow-sm shadow-slate-50">
      <View className="flex-row justify-between items-start mb-3">
        <View className="flex-row items-center gap-3">
          <Image source={{ uri: item.payment_method?.image }} className="w-10 h-10 rounded-full bg-slate-100" />
          <View>
            <AppText className="text-sm font-manrope-extrabold text-slate-800">{item.method_name}</AppText>
            <AppText className="text-[10px] text-slate-400 font-manrope-bold uppercase tracking-tighter">#{item.payment_identifier}</AppText>
          </View>
        </View>
        <StatusBadge status={item.status} />
      </View>

      <View className="flex-row justify-between items-end pt-2 border-t border-slate-50">
        <View>
          <AppText className="text-[10px] text-slate-400 font-manrope-bold uppercase">{new Date(item.created_at).toLocaleDateString()}</AppText>
          <AppText className="text-[10px] text-slate-400 font-manrope-medium">{new Date(item.created_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</AppText>
        </View>
        <View className="items-end">
          <AppText className="text-lg font-manrope-extrabold text-slate-900">
            {currency.symbol}
            {translateNumber(Number(item.amount).toFixed(2))}
          </AppText>
          <AppText className="text-[10px] text-slate-400 font-manrope-bold">
            Payable: {translateNumber(item.payable)} {item.currency}
          </AppText>
        </View>
      </View>
    </View>
  );
};

export default function DepositScreen() {
  const insets = useSafeAreaInsets();
  const { primary, success, danger } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { currency: siteCurrency } = useCurrency();
  const { handleKycError } = useKycCheck();

  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<Deposit[]>([]);
  const [showModal, setShowModal] = useState(false);

  // New Deposit Form State
  const [step, setStep] = useState(1);
  const [selectedGateway, setSelectedGateway] = useState<PaymentMethod | null>(null);
  const [amount, setAmount] = useState("");
  const [targetCurrency, setTargetCurrency] = useState(siteCurrency.code);
  const [convertedValue, setConvertedValue] = useState("");
  const [isConverting, setIsConverting] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showWebView, setShowWebView] = useState(false);
  const [paymentUrl, setPaymentUrl] = useState("");
  const [showStripeModal, setShowStripeModal] = useState(false);
  const [stripeConfig, setStripeConfig] = useState<any>(null);

  // Queries
  const { data, isLoading, isFetching, refetch } = useGetQuery({
    url: "/client/deposits",
    params: { page, search: search || undefined },
  });

  const { data: methodsData } = useGetQuery({ url: "/client/payments/methods" });
  const paymentMethods = Array.isArray(methodsData) ? methodsData : [];

  const { mutate: createDeposit } = useQueryMutation({ url: "/client/deposits" });
  const { mutate: convertCurrency } = useQueryMutation({ url: `/client/payments/currency-convert/${targetCurrency}` });

  useEffect(() => {
    if (data?.data) {
      if (page === 1) setItems(data.data);
      else setItems((prev) => [...prev, ...data.data]);
    }
  }, [data, page]);

  const onRefresh = useCallback(() => {
    setPage(1);
    refetch();
  }, [refetch]);

  const loadMore = () => {
    if (data?.current_page < data?.last_page && !isFetching) {
      setPage((prev) => prev + 1);
    }
  };

  const handleCreateDeposit = () => {
    Keyboard.dismiss();
    if (!selectedGateway || !amount) return;

    setIsSubmitting(true);
    const num = Number(amount);

    createDeposit(
      {
        amount: num,
        currency: targetCurrency,
        gateway: selectedGateway.slug,
      },
      {
        onSuccess: ({ data }) => {
          setIsSubmitting(false);
          setShowModal(false);
          if (data?.payment_url) {
            showToast({
              type: "success",
              text: tran("Redirecting to Payment"),
            });
            setPaymentUrl(data.payment_url);
            setShowWebView(true);
          } else if (data?.client_secret && data?.public_key) {
            setStripeConfig({
              client_secret: data.client_secret,
              public_key: data.public_key,
            });
            setShowStripeModal(true);
          }
          refetch();
        },
        onError: (err: any) => {
          setIsSubmitting(false);
          if (handleKycError(err)) return;

          const response = err?.response?.data;
          if (response?.type === "profile_incomplete") {
            showToast({
              type: "error",
              text: tran(response?.message || "Please complete your profile information before depositing."),
            });
            router.push("/(tabs)/account");
          } else {
            showToast({
              type: "error",
              text: tran(response?.message || err?.message || "Failed to initiate deposit"),
            });
          }
        },
      },
    );
  };

  const totalAmount = useMemo(() => {
    const num = Number(amount) || 0;
    if (!selectedGateway) return num;
    const percentCharge = Number(selectedGateway.percent_charge) || 0;
    const fixedCharge = Number(selectedGateway.fixed_charge) || 0;
    const charge = (num * percentCharge) / 100 + fixedCharge;
    return num + charge;
  }, [amount, selectedGateway]);

  useEffect(() => {
    if (targetCurrency !== siteCurrency.code && totalAmount > 0) {
      setIsConverting(true);
      convertCurrency(
        { amount: totalAmount, updatedUrl: `/client/payments/currency-convert/${targetCurrency}` },
        {
          onSuccess: (res: any) => {
            setConvertedValue(res?.data?.amount_with_currency || "");
            setIsConverting(false);
          },
          onError: () => {
            setConvertedValue("");
            setIsConverting(false);
          },
        },
      );
    } else {
      setConvertedValue("");
    }
  }, [totalAmount, targetCurrency, siteCurrency.code]);

  return (
    <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
      <View className="px-4 pt-2 pb-4 flex-row justify-between items-center">
        <View className="flex-1">
          <BackButtonTitle title={tran("Deposits")} />
        </View>
        <Pressable
          onPress={() => {
            setStep(1);
            setAmount("");
            setSelectedGateway(null);
            setShowModal(true);
          }}
          className="bg-slate-900 rounded-2xl flex-row items-center px-4 py-2.5 gap-2"
        >
          <View pointerEvents="none">
            <PlusIcon size={16} color="white" weight="bold" />
          </View>
          <AppText className="text-white font-manrope-bold text-xs">New Deposit</AppText>
        </Pressable>
      </View>

      <View className="px-4 pb-6">
        <View className="flex-row items-center bg-slate-50 border border-slate-100 rounded-[22px] px-4 py-1.5 shadow-sm shadow-slate-50">
          <MagnifyingGlassIcon size={20} color="#64748b" weight="bold" />
          <TextInput
            className="flex-1 h-12 ml-2 font-manrope-semibold text-slate-800"
            placeholder={tran("Search by ID...")}
            placeholderTextColor="#94a3b8"
            value={search}
            onChangeText={(text) => {
              setSearch(text);
              setPage(1);
            }}
          />
        </View>
      </View>

      <FlatList
        data={items}
        keyExtractor={(item, index) => `${item.id}-${index}`}
        renderItem={({ item }) => <DepositCard item={item} />}
        contentContainerStyle={{
          paddingHorizontal: 16,
          paddingBottom: insets.bottom + 40,
          flexGrow: 1,
        }}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={Boolean(isFetching && page === 1)} onRefresh={onRefresh} tintColor={primary.base} />}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        ListEmptyComponent={
          !isLoading && !isFetching && data && items.length === 0 ? (
            <View className="flex-1 justify-center py-20">
              <NoDataFound title={tran("No Deposits Found")} description={tran("Your deposit history will appear here.")} bordered={false} />
            </View>
          ) : isLoading && page === 1 ? (
            <View className="gap-y-4">
              {[1, 2, 3, 4, 5].map((i) => (
                <View key={i} className="h-32 bg-slate-50 rounded-[28px] animate-pulse border border-slate-100" />
              ))}
            </View>
          ) : null
        }
        ListFooterComponent={
          isFetching && page > 1 ? (
            <View className="py-6 items-center">
              <ActivityIndicator color={primary.base} />
            </View>
          ) : null
        }
      />

      <BottomSheet visible={showModal} onClose={() => setShowModal(false)} title={tran("Deposit Funds")} subtitle={tran("Add money to your wallet instantly")} scrollable>
        <View className="pb-10 pt-2">
          {step === 1 ? (
            <View>
              <AppText className="text-slate-500 font-manrope-bold text-[10px] uppercase mb-4 tracking-widest">Select Method</AppText>
              <View className="flex-row flex-wrap gap-3">
                {paymentMethods.map((gateway) => (
                  <Pressable
                    key={gateway.id}
                    onPress={() => {
                      setSelectedGateway(gateway);
                      setTargetCurrency(gateway.supported_currencies[0] || siteCurrency.code);
                      setStep(2);
                    }}
                    className="w-[48%] bg-white border border-slate-100 p-4 rounded-[24px] items-center justify-center shadow-sm shadow-slate-50"
                  >
                    <Image source={{ uri: gateway.image }} className="w-12 h-12 rounded-full mb-3 bg-slate-50" />
                    <AppText className="font-manrope-extrabold text-slate-800 text-center">{gateway.name}</AppText>
                    <View className="mt-1 flex-row items-center gap-1">
                      <AppText className="text-[10px] text-slate-400 font-manrope-bold">Instant</AppText>
                      <CaretRightIcon size={10} color="#94a3b8" weight="bold" />
                    </View>
                  </Pressable>
                ))}
              </View>
            </View>
          ) : (
            <View>
              <Pressable onPress={() => setStep(1)} className="flex-row items-center gap-1 mb-6">
                <AppText className="text-primary.base font-manrope-bold text-xs" style={{ color: primary.base }}>
                  {tran("Change Method")}
                </AppText>
              </Pressable>

              <View className="flex-row items-center gap-3 mb-4">
                <View className="flex-1 bg-slate-50 border border-slate-100 rounded-[22px] px-5 py-2">
                  <AppText className="text-[10px] text-slate-400 font-manrope-bold uppercase mb-0.5">Amount ({siteCurrency.code})</AppText>
                  <TextInput className="text-2xl font-manrope-extrabold text-slate-900 h-16" placeholder="0.00" keyboardType="numeric" value={amount} onChangeText={setAmount} />
                </View>
                <View className="min-w-[100px]">
                  <AppText className="text-[10px] text-slate-400 font-manrope-bold uppercase mb-1.5 ml-1">Currency</AppText>
                  <View className="bg-slate-50 border border-slate-100 rounded-2xl px-3 h-[52px] justify-center">
                    <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                      {(selectedGateway?.supported_currencies || [siteCurrency.code]).map((cur) => (
                        <Pressable
                          key={cur}
                          onPress={() => setTargetCurrency(cur)}
                          className={`px-3 py-1.5 rounded-lg mr-2 ${targetCurrency === cur ? "bg-slate-900" : "bg-white border border-slate-100"}`}
                        >
                          <AppText className={`text-xs font-manrope-bold ${targetCurrency === cur ? "text-white" : "text-slate-600"}`}>{cur}</AppText>
                        </Pressable>
                      ))}
                    </ScrollView>
                  </View>
                </View>
              </View>

              <View className="bg-slate-50 rounded-[28px] p-5 border border-slate-100 space-y-3">
                <View className="flex-row justify-between items-center">
                  <AppText className="text-slate-400 text-xs font-manrope-bold uppercase">Estimated Total</AppText>
                  <AppText className="text-slate-900 font-manrope-extrabold">
                    {siteCurrency.symbol}
                    {translateNumber((totalAmount ?? 0).toFixed(2))}
                  </AppText>
                </View>

                {isConverting ? (
                  <View className="flex-row justify-between items-center pt-1">
                    <AppText className="text-primary.base text-[10px] font-manrope-bold uppercase" style={{ color: primary.base }}>
                      Converting...
                    </AppText>
                    <ActivityIndicator size="small" color={primary.base} />
                  </View>
                ) : convertedValue ? (
                  <View className="flex-row justify-between items-center bg-white/50 p-3 rounded-2xl border border-slate-100">
                    <AppText className="text-slate-500 text-[10px] font-manrope-bold uppercase">Payable in {targetCurrency}</AppText>
                    <AppText className="text-primary.base font-manrope-extrabold" style={{ color: primary.base }}>
                      {convertedValue}
                    </AppText>
                  </View>
                ) : null}

                <View className="flex-row justify-between items-center opacity-60">
                  <AppText className="text-slate-400 text-[10px] font-manrope-bold uppercase">Method Fee</AppText>
                  <AppText className="text-slate-900 font-manrope-bold text-[10px]">
                    {selectedGateway?.percent_charge ?? 0}% + {siteCurrency.symbol}
                    {selectedGateway?.fixed_charge ?? 0}
                  </AppText>
                </View>
                <View className="pt-3 border-t border-slate-200">
                  <AppText className="text-[10px] text-slate-400 font-manrope-medium italic">
                    * Min: {selectedGateway?.min ?? 0} - Max: {selectedGateway?.max ?? 0} {siteCurrency.code}
                  </AppText>
                </View>
              </View>

              <View className="mt-10">
                <Button
                  text={`${tran("Deposit with")} ${selectedGateway?.name}`}
                  onPress={handleCreateDeposit}
                  isLoading={isSubmitting || isConverting}
                  disabled={!amount || Number(amount) < (selectedGateway?.min || 0) || isConverting}
                />
              </View>
            </View>
          )}
        </View>
      </BottomSheet>

      <Modal animationType="slide" visible={showWebView} onRequestClose={() => setShowWebView(false)}>
        <SafeAreaView style={{ flex: 1, backgroundColor: "white" }}>
          <View className="flex-row items-center justify-between px-4 py-3 border-b border-slate-100">
            <AppText className="font-manrope-extrabold text-lg">Secure Payment</AppText>
            <Pressable onPress={() => setShowWebView(false)} hitSlop={10} className="p-2">
              <View pointerEvents="none">
                <XIcon size={24} color="#1e293b" weight="bold" />
              </View>
            </Pressable>
          </View>
          <WebView
            source={{ uri: paymentUrl }}
            onNavigationStateChange={(navState) => {
              const url = navState.url;

              if (url.includes("status=success")) {
                setShowWebView(false);
                setStep(1);
                setAmount("");
                setSelectedGateway(null);
                refetch();
                router.push({
                  pathname: "/(screens)/payment/Checkout",
                  params: { status: "success" },
                });
              } else if (url.includes("status=cancel")) {
                setShowWebView(false);
                router.push({
                  pathname: "/(screens)/payment/Checkout",
                  params: { status: "cancel" },
                });
              } else if (url.includes("status=failed")) {
                setShowWebView(false);
                router.push({
                  pathname: "/(screens)/payment/Checkout",
                  params: { status: "failed" },
                });
              }
            }}
            startInLoadingState
            renderLoading={() => (
              <View className="absolute inset-0 items-center justify-center bg-white/80">
                <ActivityIndicator size="large" color={primary.base} />
              </View>
            )}
          />
        </SafeAreaView>
      </Modal>

      <BottomSheet visible={showStripeModal} onClose={() => setShowStripeModal(false)} title={tran("Credit / Debit Card")} subtitle={tran("Enter your card information securely")} scrollable>
        <View className="pb-10 pt-2">
          <Stripe config={stripeConfig} setShowCheckoutModal={setShowStripeModal} />
        </View>
      </BottomSheet>
    </View>
  );
}
