import { privateInstance } from "@/configs/axiosConfig";
import { getQueryClient } from "@/configs/query-client";
import { useKycCheck } from "@/hooks/useKycCheck";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { showToast } from "@/utils/toast";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { InfoIcon, MagnifyingGlassIcon, UserIcon, XIcon } from "phosphor-react-native";
import { useCallback, useEffect, useState } from "react";
import { ActivityIndicator, KeyboardAvoidingView, Modal, Platform, Pressable, ScrollView, Text, TextInput, TouchableOpacity, View } from "react-native";
import Button from "../ui/Button";

interface User {
  id: number;
  full_name: string;
  username: string;
  email: string;
}

interface TransferShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  share_id: number;
  project_id: number;
  share_value: number;
}

export default function TransferShareModal({
  isOpen,
  onClose,
  share_id,
  project_id,
  share_value,
}: TransferShareModalProps) {
  const { primary, secondary } = useColor();
  const { tran } = useTranslations();
  const { currency, format } = useCurrency();
  const [search, setSearch] = useState("");
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [showKycError, setShowKycError] = useState(false);
  const { requireKyc, handleKycError, kycStatus } = useKycCheck();
  const { appInfo } = useAuthStore((state: any) => state);

  const commissionPercentage = Number(appInfo?.application_info?.share_transfer_commission ?? 0);
  const commissionCharge = share_value * (commissionPercentage / 100);

  const { mutate, isLoading } = useQueryMutation({
    url: "/client/transfers",
  });

  const fetchUsers = useCallback(
    async (query: string, pageNum: number, append: boolean) => {
      if (pageNum === 1) setIsSearching(true);
      else setIsLoadingMore(true);

      try {
        const q = query.trim().toLowerCase();
        const url = `/client/transfers/users?page=${pageNum}${q ? `&search=${encodeURIComponent(q)}` : ""}`;
        const res = await privateInstance.get(url);
        const responseData = res.data?.data || res.data || {};

        let nextUsers: User[] = [];
        let currentPage = 1;
        let lastPage = 1;

        if (Array.isArray(responseData)) {
          nextUsers = responseData;
        } else if (Array.isArray(responseData.data)) {
          nextUsers = responseData.data;
          currentPage = responseData.current_page || 1;
          lastPage = responseData.last_page || 1;
        }

        setUsers((prev) => (append ? [...prev, ...nextUsers] : nextUsers));
        setHasMore(currentPage < lastPage);
        setPage(currentPage);
      } catch (err) {
        console.warn("User search failed:", err);
        if (!append) setUsers([]);
        setHasMore(false);
      } finally {
        setIsSearching(false);
        setIsLoadingMore(false);
      }
    },
    [],
  );

  useEffect(() => {
    if (!isOpen) return;
    if (search.length < 1) {
      setUsers([]);
      setHasMore(false);
      return;
    }
    const timer = setTimeout(() => {
      fetchUsers(search, 1, false);
    }, 400);
    return () => clearTimeout(timer);
  }, [search, isOpen, fetchUsers]);

  useEffect(() => {
    if (isOpen) {
      setSearch("");
      setUsers([]);
      setSelectedUser(null);
      setTermsAccepted(false);
      setShowKycError(false);
      setPage(1);
      setHasMore(false);
    }
  }, [isOpen]);

  const loadMore = () => {
    if (isLoadingMore || !hasMore) return;
    fetchUsers(search, page + 1, true);
  };

  const handleConfirm = () => {
    if (!selectedUser) {
      showToast({ type: "error", text: tran("Please select a recipient") });
      return;
    }

    if (!termsAccepted) {
      showToast({ type: "error", text: tran("You must accept the Terms & Conditions before transfer.") });
      return;
    }

    if (kycStatus !== "verified") {
      setShowKycError(true);
      requireKyc();
      return;
    }

    mutate(
      { share_id, project_id, to_user_id: selectedUser.id },
      {
        onSuccess: (res) => {
          showToast({ type: "success", text: tran(res?.message || "Share transferred successfully!") });
          getQueryClient().invalidateQueries({
            predicate: (query) => query.queryKey.some((key) => typeof key === "string" && (key.includes("/client/projects") || key.includes("/projects"))),
          });
          onClose();
        },
        onError: (err: any) => {
          if (handleKycError(err)) {
            setShowKycError(true);
            return;
          }
          showToast({ type: "error", text: err?.response?.data?.message || err?.message || tran("Failed to transfer share") });
        },
      },
    );
  };

  return (
    <Modal visible={isOpen} animationType="fade" transparent={true} onRequestClose={onClose}>
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} className="flex-1 bg-black/60 justify-center items-center p-6">
        <View className="bg-white rounded-[32px] w-full max-h-[90%] shadow-2xl relative overflow-hidden">
          <View className="px-6 pt-7 pb-5 flex-row justify-between items-center border-b border-slate-50">
            <View>
              <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Transfer Share")}</Text>
              <View className="flex-row items-center gap-1.5 mt-1">
                <InfoIcon size={14} color="#64748b" weight="bold" />
                <Text className="text-xs font-manrope-bold text-slate-500 uppercase tracking-wider">{tran("Secure Transfer")}</Text>
              </View>
            </View>
            <Pressable onPress={onClose} className="w-10 h-10 bg-slate-50 rounded-full items-center justify-center">
              <XIcon size={20} color="#64748b" weight="bold" />
            </Pressable>
          </View>

          <ScrollView className="px-6 pt-5" showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
            <View className="bg-slate-50 rounded-2xl p-4 border border-slate-100 mb-5">
              <Text className="text-xs font-manrope-semibold text-slate-500 leading-relaxed">
                {tran("Transfer ownership to another verified user. Recipients must have an active platform account.")}
              </Text>
            </View>

            <View className="mb-5 flex-row justify-between items-center bg-white border border-slate-100 rounded-2xl px-4 py-3">
              <Text className="text-sm font-manrope-bold text-slate-900">{tran("Commission Charge")}</Text>
              <Text className="text-sm font-manrope-bold text-slate-700">
                {currency.symbol_position === "left" ? currency.symbol : ""}
                {format(commissionCharge, { showSymbol: false })}
                {currency.symbol_position !== "left" ? currency.symbol : ""}
                <Text className="text-xs font-manrope-semibold text-slate-400">  ({commissionPercentage}%)</Text>
              </Text>
            </View>

            <View className="mb-6">
              <Text className="text-sm font-manrope-bold text-slate-900 mb-2.5">{tran("Select Recipient")}</Text>
              <View className="relative">
                <View className="absolute left-4 top-1/2 -translate-y-1/2 z-10">
                  <MagnifyingGlassIcon size={20} color="#94a3b8" />
                </View>
                <TextInput
                  value={search}
                  onChangeText={setSearch}
                  placeholder={tran("Search by name, email or username")}
                  className="bg-slate-50 border border-slate-100 rounded-2xl h-14 pl-12 pr-4 font-manrope-semibold text-slate-900"
                />
              </View>

              <View className="mt-3 max-h-56 bg-white border border-slate-100 rounded-2xl overflow-hidden shadow-sm">
                {isSearching ? (
                  <View className="py-8">
                    <ActivityIndicator color={primary.base} />
                  </View>
                ) : users.length > 0 ? (
                  <ScrollView
                    nestedScrollEnabled
                    className="max-h-56"
                    onScroll={({ nativeEvent }) => {
                      const { layoutMeasurement, contentOffset, contentSize } = nativeEvent;
                      const paddingToBottom = 40;
                      if (layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom) {
                        loadMore();
                      }
                    }}
                    scrollEventThrottle={100}
                  >
                    {users.map((item) => (
                      <Pressable
                        key={item.id}
                        onPress={() => {
                          setSelectedUser(item);
                          setSearch(`${item.full_name} (${item.username})`);
                          setUsers([]);
                        }}
                        className={`px-4 py-3.5 border-b border-slate-50 flex-row items-center gap-3 active:bg-slate-50 ${selectedUser?.id === item.id ? "bg-slate-50" : ""}`}
                      >
                        <View className="w-9 h-9 rounded-full bg-slate-100 items-center justify-center">
                          <UserIcon size={18} color="#64748b" weight="duotone" />
                        </View>
                        <View className="flex-1">
                          <Text className="text-sm font-manrope-bold text-slate-900">{item.full_name}</Text>
                          <Text className="text-[11px] font-manrope-semibold text-slate-400">{item.email}</Text>
                        </View>
                        {selectedUser?.id === item.id && <Ionicons name="checkmark-circle" size={20} color={secondary.base} />}
                      </Pressable>
                    ))}
                    {isLoadingMore && (
                      <View className="py-3">
                        <ActivityIndicator size="small" color={primary.base} />
                      </View>
                    )}
                  </ScrollView>
                ) : search.length > 0 && !isSearching ? (
                  <View className="py-6 items-center">
                    <Text className="text-xs font-manrope-semibold text-slate-400">{tran("No users found")}</Text>
                  </View>
                ) : null}
              </View>
            </View>

            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() => setTermsAccepted((prev) => !prev)}
              className="flex-row items-start gap-3 mb-5 bg-slate-50/50 p-4 rounded-2xl border border-dashed border-slate-200"
            >
              <View
                className="w-6 h-6 rounded-md border items-center justify-center"
                style={{
                  backgroundColor: termsAccepted ? secondary.base : "#ffffff",
                  borderColor: termsAccepted ? secondary.base : "#cbd5e1",
                }}
              >
                {termsAccepted && <Ionicons name="checkmark" size={16} color="white" />}
              </View>
              <View className="flex-1" pointerEvents="none">
                <Text className="text-[13px] font-manrope-semibold text-slate-600 leading-snug">
                  {tran("I accept the")} <Text className="font-manrope-bold underline" style={{ color: secondary.base }}>{tran("Terms & Conditions")}</Text>
                </Text>
              </View>
            </TouchableOpacity>

            {showKycError && (
              <View className="flex-row items-center justify-between mb-5 gap-3 bg-red-50 px-4 py-3 rounded-xl border border-red-200">
                <Text className="flex-1 text-xs font-manrope-bold text-red-600">{tran("Please complete your KYC verification first.")}</Text>
                <Pressable
                  onPress={() => {
                    onClose();
                    router.push("/(auth)/kyc");
                  }}
                >
                  <Text className="text-xs font-manrope-extrabold text-red-700 underline">{tran("KYC Verification")}</Text>
                </Pressable>
              </View>
            )}

            <View className="flex-row gap-3 mb-6">
              <View className="flex-1">
                <Button text={tran("Cancel")} type="secondary" onPress={onClose} disabled={isLoading} />
              </View>
              <View className="flex-1">
                <Button
                  text={isLoading ? tran("Processing") + "..." : tran("Confirm")}
                  type="primary"
                  onPress={handleConfirm}
                  disabled={!termsAccepted || !selectedUser || isLoading}
                />
              </View>
            </View>
          </ScrollView>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
