/* eslint-disable @typescript-eslint/no-explicit-any */
import styles from "../../Deposits/Fiat/fiat.module.scss";
import { useForm } from "@inertiajs/react";
import { useState } from "react";
import btc from "../../../../../images/btc-logo.svg";

interface CryptoWithdrawalsProps {
  togglePinModal: () => void;
  loggedInUser: {
    walletBalance: number;
    [key: string]: any;
  };
}

const CryptoWithdrawals = ({ togglePinModal, loggedInUser }: CryptoWithdrawalsProps) => {
  const { data, setData, post, processing, reset } = useForm({
    amount: "",
    wallet: "",
    method: "crypto",
    channel: "btc",
    type: "debit",
    category: "withdrawal",
    status: "pending",
  });

  const [error, setError] = useState<string | null>(null);
  const { walletBalance } = loggedInUser || {};

  // Format number for user input
  const formatNumber = (value: string): string => {
    const numeric = value.replace(/[^0-9.]/g, "");
    if (!numeric) return "";
    const parts = numeric.split(".");
    const whole = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.length > 1 ? `${whole}.${parts[1]}` : whole;
  };

  // Handle Submit
  const handleSubmit = (e: React.FormEvent) => {
  e.preventDefault();

  const numericAmount = parseFloat(data.amount.replace(/,/g, ''));
  if (!numericAmount || !data.wallet) {
    alert('Please complete all fields');
    return;
  }

  // Update form data before submitting
  setData('amount', numericAmount.toString());

  post("/transactions", {
    preserveScroll: true,
    onBefore: () => setError(null),
    onSuccess: () => {
      reset();
      togglePinModal(); // open pin confirmation
    },
    onError: (errors) => {
      console.error(errors);
      setError("An error occurred. Please try again.");
    },
  });
};


  return (
    <div className={styles["fiat"]}>
      <div className={styles["fiat__header"]}>
        <h2>Withdraw Crypto Today!</h2>
      </div>

      <form onSubmit={handleSubmit} className={styles["fiat__form"]}>
        {/* Amount */}
        <label htmlFor="amount">Amount to withdraw *</label>
        <div className={styles["fiat__form--amount"]} style={{ marginBottom: ".5rem" }}>
          <img src={btc} alt="btc logo" />
          <input
            className={styles["fiat__form--amount--input"]}
            type="text"
            value={data.amount}
            placeholder="Enter amount to withdraw"
            onChange={(e) => setData("amount", formatNumber(e.target.value))}
          />
        </div>

        {/* Wallet balance */}
        <div className={styles["fiat__form--summary"]}>
          <h6>Wallet Balance: ${Number(walletBalance || 0).toLocaleString("en-US")}</h6>
        </div>

        {/* Wallet address */}
        <div className={styles["fiat__form--wallet"]}>
          <label htmlFor="wallet">Wallet address *</label>
          <input
            type="text"
            id="wallet"
            value={data.wallet}
            placeholder="Enter your wallet address"
            onChange={(e) => setData("wallet", e.target.value)}
          />
        </div>

        {/* Error Message */}
        {error && <p style={{ color: "#d33", fontSize: ".9rem", marginTop: "0.5rem" }}>{error}</p>}

        <br />
        <small>
          By clicking on the <strong>Proceed</strong> button, you agree to our terms and conditions.
        </small>

        <button type="submit" disabled={processing} style={{ marginTop: "1rem" }}>
          {processing ? "Processing..." : "Proceed To Withdraw"}
        </button>
      </form>
    </div>
  );
};

export default CryptoWithdrawals;
