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

interface CancelListingModalProps {
  isOpen: boolean;
  onClose: () => void;
  listingId: number;
  projectTitle: string;
  numberOfShares: number;
  price: number;
}

export default function CancelListingModal({
  isOpen,
  onClose,
  listingId,
  projectTitle,
  numberOfShares,
  price,
}: CancelListingModalProps) {
  const { primary } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { currency } = useCurrency();
  const [confirmed, setConfirmed] = useState(false);
  const [quantity, setQuantity] = useState(1);

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

  const handleCancel = () => {
    if (!confirmed) {
      // toast.error(tran("Please confirm cancellation"));
      return;
    }

    const payload = {
      project_id: listingId,
      number_of_shares: quantity,
      price: Number(price),
      _method: "delete",
    };

    mutate(payload, {
      onSuccess: (res) => {
        showToast({
          type: "success",
          text: res?.message || tran("Listing cancelled successfully"),
        });
        handleClose();
      },
      onError: (err: any) => {
        showToast({
          type: "error",
          text: err?.response?.data?.message || tran("Failed to cancel listing"),
        });
      },
    });
  };

  const handleClose = () => {
    setConfirmed(false);
    setQuantity(1);
    onClose();
  };

  if (!isOpen) return null;

  const totalValue = quantity * price;

  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="flex-row items-center justify-between mb-6">
            <View>
              <Text className="text-xl font-manrope-extrabold text-slate-900 leading-tight">
                {tran("Cancel Listing")}
              </Text>
              <Text className="text-sm font-manrope text-slate-500 mt-1">
                {tran("Select shares to return to your account")}
              </Text>
            </View>
            <Pressable 
              onPress={handleClose} 
              className="w-10 h-10 items-center justify-center rounded-full bg-slate-50"
            >
              <XIcon size={20} color="#64748b" weight="bold" />
            </Pressable>
          </View>

          <View className="pb-2">
            {/* Listing Details */}
            <View 
              className="rounded-xl p-4 border mb-6"
              style={{ backgroundColor: primary[5], borderColor: primary[20] }}
            >
              <Text className="text-lg font-manrope-bold text-slate-900 mb-4">
                {projectTitle}
              </Text>

              <View className="flex-row items-center justify-between mb-2">
                <Text className="text-sm font-manrope-medium text-slate-500">
                  {tran("Price Per Share")}
                </Text>
                <Text className="text-sm font-manrope-bold text-slate-900">
                  {currency.symbol}{translateNumber(price)}
                </Text>
              </View>
              <View className="flex-row items-center justify-between pt-2 border-t border-slate-200/50">
                <Text className="text-sm font-manrope-medium text-slate-500">
                  {tran("Total Value to Cancel")}
                </Text>
                <Text className="text-lg font-manrope-bold text-red-500">
                  {currency.symbol}{translateNumber(totalValue)}
                </Text>
              </View>
            </View>

            {/* Quantity Selector */}
            <View className="mb-6">
              <View className="flex-row items-center justify-between mb-2">
                <Text className="text-sm font-manrope-semibold text-slate-900">
                  {tran("Quantity to Cancel")}
                </Text>
                <Text className="text-sm font-manrope-medium text-slate-500">
                  {tran("Max")}: <Text className="font-manrope-bold text-slate-900">{translateNumber(numberOfShares)}</Text>
                </Text>
              </View>
              <QuantitySelector
                pricePerItem={price}
                quantity={quantity}
                onQuantityChange={setQuantity}
                min={1}
                max={numberOfShares}
                showTotal={false}
              />
            </View>

            {/* Info Box */}
            <View className="flex-row items-start gap-3 p-3 bg-blue-50/50 rounded-xl border border-blue-100 mb-6">
              <InfoIcon size={20} color="#3b82f6" weight="regular" />
              <Text className="flex-1 text-xs font-manrope text-blue-600 leading-relaxed">
                {tran("Once cancelled, these shares will return to your active portfolio and will be removed from the public marketplace.")}
              </Text>
            </View>

            {/* Confirmation Toggle */}
            <View className="flex-row items-start mb-6 pt-2">
              <Pressable className="flex-row items-center pt-0.5" onPress={() => setConfirmed(!confirmed)}>
                <View
                  className="h-6 w-6 rounded-md border items-center justify-center mr-3"
                  style={{
                    backgroundColor: confirmed ? primary.base : "white",
                    borderColor: confirmed ? primary.base : "#cbd5e1",
                  }}
                >
                  {confirmed ? <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 understand and want to cancel")}{" "}
                <Text className="font-manrope-bold text-slate-900">
                  {translateNumber(quantity)} {tran("share(s)")}
                </Text>
              </Text>
            </View>

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