import { getQueryClient } from "@/configs/query-client";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useKycCheck } from "@/hooks/useKycCheck";
import { useTranslations } from "@/providers/TranslationProviders";
import { showToast } from "@/utils/toast";
import { Ionicons } from "@expo/vector-icons";
import { useEffect, useState } from "react";
import { KeyboardAvoidingView, Modal, Platform, Pressable, Text, TextInput, View } from "react-native";
import QuantitySelector from "../sections/quantity-selector";
import Button from "../ui/Button";

interface ListShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  project_id: number;
  active_shares: number;
}

const ListShareModal = ({ isOpen, onClose, project_id, active_shares }: ListShareModalProps) => {
  const { requireKyc, handleKycError } = useKycCheck();
  const [quantity, setQuantity] = useState(1);
  const [listingPrice, setListingPrice] = useState<number | null>(null);
  const [termsAccepted, setTermsAccepted] = useState(false);
  const { primary } = useColor();
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();

  const { mutate, isLoading } = useQueryMutation({
    url: `/client/listings`,
  });

  // Track previous isOpen state to detect when modal opens
  // Track previous isOpen state to detect when modal opens
  useEffect(() => {
    if (isOpen) {
      setQuantity(1);
      setListingPrice(null);
      setTermsAccepted(false);
    }
  }, [isOpen]);

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

    if (!requireKyc()) return;

    if (!listingPrice || listingPrice <= 0) {
      showToast({
        type: "error",
        text: tran("Please set a valid price for your shares."),
      });
      return;
    }

    const payload = {
      project_id,
      price: Number(listingPrice),
      number_of_shares: quantity,
    };

    mutate(payload, {
      onSuccess: () => {
        onClose();
        getQueryClient().invalidateQueries({ queryKey: [`/client/projects`] });
        getQueryClient().invalidateQueries({
          queryKey: [`/marketplace/listings`],
        });
        showToast({
          type: "success",
          text: tran("Share listed successfully"),
        });
      },
      onError: (err: any) => {
        if (handleKycError(err)) return;
        showToast({
          type: "error",
          text: err?.response?.data?.message || err?.message || tran("Failed to list share"),
        });
      },
    });
  };

  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-[90%] max-h-[85%] shadow-lg">
          <View className="flex-row justify-between items-center mb-6">
            <View>
              <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("List Share")}</Text>
              <Text className="text-sm font-manrope text-slate-500">{tran("Specify price and quantity to list")}</Text>
            </View>
          </View>

          <View className="pb-2">
            <View className="mb-6">
              <Text className="text-sm font-manrope-medium text-slate-700 mb-2">{tran("Price Per Share")}:</Text>
              <View className="relative flex-row justify-start items-center gap-2 border border-slate-200 rounded-xl px-4 py-1 bg-slate-50">
                <Text className="text-lg font-manrope text-slate-500">{currency.symbol}</Text>
                <TextInput
                  keyboardType="numeric"
                  value={listingPrice !== null ? String(listingPrice) : ""}
                  onChangeText={(text) => setListingPrice(text ? Number(text) : null)}
                  className="flex-1 h-12 text-lg font-manrope-bold text-slate-900"
                  placeholder="0.00"
                  placeholderTextColor="#94a3b8"
                />
              </View>
            </View>

            <View className="mb-6">
              <View className="flex-row items-center justify-between mb-3">
                <Text className="text-sm font-manrope-semibold text-slate-900">{tran("Number of Shares")}</Text>
                <Text className="text-sm text-slate-500 font-manrope">
                  {tran("Available")}: <Text className="font-manrope-bold text-slate-900">{translateNumber(active_shares)}</Text>
                </Text>
              </View>
              <View className="w-full">
                <QuantitySelector pricePerItem={listingPrice || 0} quantity={quantity} onQuantityChange={setQuantity} max={active_shares} min={1} showTotal={false} />
              </View>

              <View className="gap-2 flex-row justify-between items-center mt-4">
                {[5, 10, 25, 50].map((opt) => (
                  <Pressable
                    key={opt}
                    onPress={() => setQuantity(Math.min(opt, active_shares))}
                    disabled={opt > active_shares}
                    className={`py-2 px-1 rounded-xl border transition-colors ${quantity === opt ? "" : "border-slate-200 bg-white"} disabled:opacity-50 disabled:bg-slate-100 flex-1`}
                    style={{
                      borderColor: quantity === opt ? primary.base : "#e2e8f0",
                      backgroundColor: quantity === opt ? primary[5] : "white",
                    }}
                  >
                    <Text
                      className="text-center font-manrope-medium text-sm"
                      style={{
                        color: quantity === opt ? primary.base : "#64748b",
                      }}
                    >
                      {opt} {tran("shares")}
                    </Text>
                  </Pressable>
                ))}
              </View>
            </View>

            <View className="flex-row items-start 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">I agree to the Terms of Service, Privacy Policy, and Risk Disclosure.</Text>
            </View>

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

export default ListShareModal;
