import Button from "@/components/ui/Button";
import { useQueryClient } from "@tanstack/react-query";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useKycCheck } from "@/hooks/useKycCheck";
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 { useState } from "react";
import { KeyboardAvoidingView, Modal, Platform, Pressable, Text, View } from "react-native";
import QuantitySelector from "../quantity-selector";

interface InvestConfirmModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  projectSlug: string;
  shareCount?: number;
  shareValue: number;
  max: number;
  onQuantityChange?: (quantity: number) => void;
}

export default function InvestConfirmModal({ isOpen, onClose, projectSlug, shareCount = 1, shareValue, max, onQuantityChange }: InvestConfirmModalProps) {
  const { tran, translateNumber } = useTranslations();
  const { currency } = useCurrency();
  const { primary } = useColor();
  const [quantity, setQuantity] = useState(shareCount);
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [insufficientBalanceAmount, setInsufficientBalanceAmount] = useState<number | null>(null);
  const { requireKyc, handleKycError } = useKycCheck();

  // Track previous props for render-time state adjustment
  const [prevIsOpen, setPrevIsOpen] = useState(isOpen);
  const [prevShareCount, setPrevShareCount] = useState(shareCount);

  // Adjust state during render when props change
  if (isOpen !== prevIsOpen || shareCount !== prevShareCount) {
    setPrevIsOpen(isOpen);
    setPrevShareCount(shareCount);
    if (isOpen) {
      setQuantity(shareCount);
      setTermsAccepted(false);
      setInsufficientBalanceAmount(null);
    }
  }

  const { user, isAuthenticated, getUser } = useAuthStore((state: any) => state);
  const queryClient = useQueryClient();

  const { mutate, isLoading } = useQueryMutation({
    url: `projects/${projectSlug}/invest`,
  });

  const handleQuantityChange = (newQuantity: number) => {
    setQuantity(newQuantity);
    onQuantityChange?.(newQuantity);
  };

  const handleConfirm = () => {
    if (!isAuthenticated) {
      onClose();
      return;
    }

    if (!termsAccepted) {
      return;
    }

    if (!requireKyc()) return;

    // Calculate total investment amount
    const totalAmount = shareValue * quantity;

    // Check if user has insufficient balance
    if ((user?.balance || 0) < totalAmount) {
      setInsufficientBalanceAmount(totalAmount);
      return;
    }

    const payload = {
      terms: termsAccepted ? 1 : 0,
      number_of_shares: quantity,
    };

    mutate(payload, {
      onSuccess: async () => {
        onClose();

        // Invalidate project list and this project's detail query
        queryClient.invalidateQueries({ queryKey: ["/projects"] });
        queryClient.invalidateQueries({ queryKey: [`/projects/${projectSlug}`] });

        // Update user balance if there's a getUser method
        if (getUser) {
          await getUser();
        }

        showToast({
          type: "success",
          text: tran("Investment successful") + "!",
        });
      },
      onError: (error: any) => {
        if (handleKycError(error)) return;
        showToast({
          type: "error",
          text: error?.response?.data?.message || tran("Investment failed"),
        });
      },
    });
  };

  const handleCancel = () => {
    onClose();
  };

  const quickSelectOptions = [5, 10, 25, 50];

  // Placeholder fees - replace with actual logic if available
  const platformFee = 0;
  const processingFee = 0;
  const totalAmount = shareValue * quantity + platformFee + processingFee;

  if (!isOpen) return null;

  return (
    <Modal animationType="fade" transparent={true} visible={isOpen} onRequestClose={onClose}>
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} className="flex-1 justify-center items-center bg-black/50">
        <View className="bg-white rounded-2xl p-6 w-[95%] max-h-[90%] shadow-lg">
          <View className="mb-6">
            <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Confirm Investment")}</Text>
            <Text className="text-sm font-manrope text-slate-500">{tran("Are you sure you want to invest in this project?")}</Text>
          </View>

          <View className="pb-2">
            {/* Quantity Selector */}
            <View className="mb-6">
              <View className="flex-row items-center justify-between mb-2">
                <Text className="text-sm font-semibold text-heading">{tran("Number of Shares")}</Text>
                <Text className="text-sm text-body-text">
                  {tran("Available")}: <Text className="font-semibold text-heading">{translateNumber(max)}</Text>
                </Text>
              </View>
              <QuantitySelector pricePerItem={shareValue} quantity={quantity} onQuantityChange={handleQuantityChange} max={max} min={1} showTotal={false} />
              {/* Quick Select Buttons */}
              <View className="flex-row gap-1 flex-wrap justify-center items-center">
                {quickSelectOptions.map((opt) => (
                  <Pressable
                    key={opt}
                    onPress={() => handleQuantityChange(Math.min(opt, max))}
                    disabled={opt > max}
                    className={`py-2 flex-1 px-1 rounded-lg text-sm border  ${quantity === opt ? " border-primary font-manrope-medium" : "border-slate-200 "} disabled:opacity-50`}
                  >
                    <Text className="text-center">
                      {opt} {tran("shares")}
                    </Text>
                  </Pressable>
                ))}
              </View>
            </View>

            {/* Cost Breakdown */}
            <View className=" rounded-xl p-5 mb-6 bg-slate-50 border border-slate-100">
              <View className="flex-row items-center justify-between">
                <Text className="font-bold text-heading">{tran("Estimated Total")}</Text>
                <Text className="text-xl font-bold text-primary">
                  {currency.symbol}
                  {translateNumber(totalAmount)}
                </Text>
              </View>
            </View>

            {insufficientBalanceAmount && (
              <View className="mb-4 bg-red-50 px-3 py-2 rounded-lg text-sm border border-red-100">
                <Text className="text-red-600 text-sm">{tran("Insufficient Balance")}</Text>
              </View>
            )}

            {/* Terms & Conditions */}
            <View className="flex-row items-center mb-6 pt-2">
              <Pressable className="flex-row items-center pt-0.5" onPress={() => setTermsAccepted(!termsAccepted)}>
                <View
                  className="h-6 w-6 rounded-md border items-center justify-center mr-3"
                  style={{
                    backgroundColor: termsAccepted ? primary.base : "white",
                    borderColor: termsAccepted ? primary.base : "#cbd5e1",
                  }}
                >
                  {termsAccepted ? <Ionicons name="checkmark" size={16} color="white" /> : null}
                </View>
              </Pressable>
              <Text className="flex-1 text-sm font-manrope text-slate-600 leading-relaxed">
                {tran("I accept the")}{" "}
                <Text onPress={() => router.push("/terms-and-conditions" as any)} className="text-primary font-manrope-medium">
                  {tran("Terms & Conditions")}
                </Text>{" "}
                {tran("and acknowledge that returns are projections, not guarantees.")}
              </Text>
            </View>

            {/* Action Buttons */}
            <View className="flex-row gap-3 pt-2">
              <View className="flex-1">
                <Button onPress={handleCancel} disabled={isLoading} text={tran("Cancel")} type="secondary" />
              </View>
              <View className="flex-1">
                <Button onPress={handleConfirm} disabled={isLoading || !termsAccepted} text={isLoading ? tran("Processing") + "..." : tran("Confirm")} />
              </View>
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
