import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "../../../../store";
import CashIn from "../../../../assets/walletCash.svg";
import { cashOutWallet } from "../../../../api/api";
import { RootState } from "../../../../store";
import SuccessModal from "../components/SuccessModel";
import usaFlag from "../../../../assets/united-states-flag-icon.svg";
import canFlag from "../../../../assets/canada-flag-icon.svg";
import Image from "next/image";

const currencyOptions = {
  USD: { symbol: "USD $", flag: usaFlag },
  CAD: { symbol: "CAD $", flag: canFlag },
};

interface ConfirmCashOutModalProps {
  onClose: () => void;
}

const ConfirmCashOutModal: React.FC<ConfirmCashOutModalProps> = ({
  onClose,
}) => {
  const [amountToAdd, setAmountToAdd] = useState<number | "">("");
  const [currency, setCurrency] = useState<"USD" | "CAD">("USD");
  const [isProcessing, setIsProcessing] = useState(false);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [error, setError] = useState<string>("");
  const dispatch: AppDispatch = useDispatch();
  const { cashWalletHistoryData } = useSelector(
    (state: RootState) => state.WalletReducer
  );
  const walletBalance = cashWalletHistoryData?.wallet_balance;

  const handleAddAmount = async () => {
    if (typeof amountToAdd !== "number" || amountToAdd <= 0) {
      setError("Please enter a valid amount.");
      return;
    }
    if (Number(amountToAdd) > Number(walletBalance)) {
      setError("Insufficient wallet balance. Please enter a smaller amount.");
      return;
    }
    try {
      setIsProcessing(true);
      await dispatch(cashOutWallet({ amount: amountToAdd, currency })).unwrap();
      setError("");
      setAmountToAdd("");
      setShowSuccessModal(true);
    } catch (error: any) {
      setError(
        error?.message || "Failed to process the cash out. Please try again."
      );
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <>
      {!showSuccessModal && (
        <div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
          <div className="bg-white w-[90%] max-w-md rounded-lg shadow-lg p-6 relative">
            <button
              onClick={onClose}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
            >
              &times;
            </button>
            <div className="text-center mb-6">
              <Image
                unoptimized
                src={CashIn}
                alt="Cash Out Icon"
                className="mx-auto mb-4"
              />
              <h2 className="text-[24px] font-semibold text-[#151D48]">
                Confirm Cash Out
              </h2>
              <p className="text-[#454545] text-[18px]">
                Please confirm your details. Money will be sent to your account.
              </p>
            </div>
            <div className="space-y-4">
              <div className="flex flex-col items-center text-gray-700">
                <span className="font-sans pb-2">Select Currency</span>
                <div className="relative w-[87%]">
                  <Image
                    unoptimized
                    src={currencyOptions[currency].flag}
                    alt="flag"
                    className="absolute right-3 top-3 w-5 h-5"
                  />
                  <select
                    value={currency}
                    onChange={(e) =>
                      setCurrency(e.target.value as "USD" | "CAD")
                    }
                    className="border border-gray-300 rounded-lg px-3 py-2 w-full shadow-sm text-lg appearance-none"
                  >
                    {Object.entries(currencyOptions).map(
                      ([code, { symbol }]) => (
                        <option
                          key={code}
                          value={code}
                          className="flex items-center"
                        >
                          {symbol}
                        </option>
                      )
                    )}
                  </select>
                </div>
                <span className="font-sans pb-2 mt-4">Enter Amount</span>
                <div className="flex items-center border border-gray-300 rounded-lg w-[87%] px-4 py-2">
                  <Image
                    unoptimized
                    src={currencyOptions[currency].flag}
                    alt={currency}
                    className="w-6 h-6 mr-2"
                  />
                  <span className="mr-2 text-lg font-medium">
                    {currencyOptions[currency].symbol}
                  </span>
                  <input
                    type="number"
                    value={amountToAdd}
                    onChange={(e) => setAmountToAdd(Number(e.target.value))}
                    placeholder="Cash out"
                    className="flex-1 outline-none text-base bg-transparent  border border-gray-300 rounded-md  w-[80%]"
                  />
                </div>
                {error && <span className="text-red-500 text-sm">{error}</span>}
              </div>
              <div className="bg-gray-100 p-4 mt-4 rounded-md">
                <p className="text-sm text-black">
                  <strong>About your earnings</strong>
                </p>
                <p className="text-sm text-[#454545]">
                  The amount shown will be transferred to your account. Currency
                  rates are managed within that.
                </p>
              </div>
            </div>
            <div className="flex justify-end space-x-4 mt-6">
              <button
                onClick={onClose}
                className="px-4 py-2 text-gray-500 border border-[#04104E] rounded-md hover:bg-[#04104E] hover:text-white"
              >
                Cancel
              </button>
              <button
                onClick={handleAddAmount}
                className="px-4 py-2 bg-[#04104E] text-white rounded-md hover:bg-[#0b144d]"
                disabled={isProcessing}
              >
                {isProcessing ? "Processing..." : "Confirm"}
              </button>
            </div>
          </div>
        </div>
      )}
      {showSuccessModal && (
        <SuccessModal
          isOpen={showSuccessModal}
          onClose={() => {
            setShowSuccessModal(false);
            onClose();
          }}
        />
      )}
    </>
  );
};

export default ConfirmCashOutModal;
