import BottomSheet from "@/components/ui/BottomSheet";
import Button from "@/components/ui/Button";
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 { showToast } from "@/utils/toast";
import { useTranslations } from "@/providers/TranslationProviders";
import { router } from "expo-router";
import { useState } from "react";
import { Pressable, Text, View } from "react-native";
import QuantitySelector from "../quantity-selector";

interface BuyShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectId: number;
  sellerId: number | null;
  price: number;
  maxShares: number;
  shareCount?: number;
  onQuantityChange?: (quantity: number) => void;
}

export default function BuyShareModal({ isOpen, onClose, projectId, sellerId, price, maxShares, shareCount = 1, onQuantityChange }: BuyShareModalProps) {
  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 } = useAuthStore((state) => state);

  const { mutate, isLoading } = useQueryMutation({
    url: `/marketplace/purchase`,
  });

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

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

    if (!termsAccepted) {
      return;
    }

    if (!requireKyc()) return;

    const totalAmount = price * quantity;

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

    const payload = {
      project_id: projectId,
      seller_id: sellerId,
      price: price,
      number_of_shares: quantity,
      terms: termsAccepted ? 1 : 0,
    };

    mutate(payload, {
      onSuccess: () => {
        onClose();
        router.push("/(tabs)/marketplace");
      },
      onError: (err: any) => {
        if (handleKycError(err)) return;
        showToast({
          type: "error",
          text: err?.response?.data?.message || err?.message || tran("Failed to purchase shares"),
        });
      },
    });
  };

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

  const quickSelectOptions = [5, 10, 25, 50];
  const totalAmount = price * quantity;

  if (!isOpen) return null;

  return (
    <BottomSheet visible={isOpen} onClose={onClose} title={`${tran("Confirm Purchase")}`} subtitle={`${tran("Are you sure you want to buy shares from this listing?")}`} scrollable={false}>
      <View className="pb-6">
        {/* 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(maxShares)}</Text>
            </Text>
          </View>
          <QuantitySelector pricePerItem={price} quantity={quantity} onQuantityChange={handleQuantityChange} max={maxShares} min={1} showTotal={false} />
          {/* Quick Select Buttons */}
          <View className="flex-row gap-1 flex-wrap justify-center items-center mt-3">
            {quickSelectOptions.map((opt) => (
              <Pressable
                key={opt}
                onPress={() => handleQuantityChange(Math.min(opt, maxShares))}
                disabled={opt > maxShares}
                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="bg-slate-50 rounded-xl p-5 mb-6">
          <View className="flex-row items-center justify-between">
            <Text className="font-bold text-slate-800">{tran("Estimated Total")}</Text>
            <Text className="text-xl font-bold text-primary">
              {currency.symbol}
              {translateNumber(totalAmount)}
            </Text>
          </View>
        </View>

        {insufficientBalanceAmount && <Text className="text-red-500 font-manrope-medium text-sm text-center mb-4">{tran("Insufficient Balance")}</Text>}

        {/* Terms & Conditions */}
        <View className="mb-6">
          <View className="flex-row items-start gap-3 p-3 rounded-lg">
            <Pressable
              onPress={() => setTermsAccepted(!termsAccepted)}
              className="w-5 h-5 rounded border items-center justify-center mt-0.5"
              style={{
                backgroundColor: termsAccepted ? primary.base : "transparent",
                borderColor: termsAccepted ? primary.base : "#cbd5e1",
              }}
            >
              {termsAccepted && <Text className="text-white text-xs font-bold">✓</Text>}
            </Pressable>
            <Text className="text-sm text-slate-600 flex-1" onPress={() => setTermsAccepted(!termsAccepted)} suppressHighlighting={true}>
              {tran("I accept the")}{" "}
              <Text onPress={() => router.push("/terms-and-conditions" as any)} className="font-manrope-medium underline" style={{ color: primary.base }}>
                {tran("Terms & Conditions")}
              </Text>{" "}
              {tran("and acknowledge that returns are projections, not guarantees.")}
            </Text>
          </View>
        </View>

        {/* Action Buttons */}
        <View className="flex-col gap-3 justify-center items-center">
          <Button onPress={handleCancel} disabled={isLoading} text={tran("Cancel")} type="secondary" />
          <Button onPress={handleConfirm} disabled={!termsAccepted || isLoading} text={isLoading ? tran("Processing") + "..." : tran("Confirm")} />
        </View>
      </View>
    </BottomSheet>
  );
}
