/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client"

import { useState, useMemo } from "react"
import styles from "./deposit-modal.module.scss"
import { router, usePage } from "@inertiajs/react"

import btcLogo from "../../../../../images/btc-logo.svg"
import ethLogo from "../../../../../images/eth-logo.svg"
import bnbLogo from "../../../../../images/bnb-logo.png"
import adaLogo from "../../../../../images/cardano-logo.png"
import usdtLogo from "../../../../../images/usdt-logo.png"

import { MdClose } from "react-icons/md"
import { FaChevronDown } from "react-icons/fa"

const cryptoLogos: Record<string, any> = {
  BTC: btcLogo,
  Ethereum: ethLogo,
  ETH: ethLogo,
  BNB: bnbLogo,
  ADA: adaLogo,
  USDT: usdtLogo,
}

interface PaymentMethod {
  id: number
  method: string
  address: string
  charges: number
  is_enabled: boolean
}

interface DepositModalProps {
  onClose: () => void
}

const DepositModal = ({ onClose }: DepositModalProps) => {
  const page = usePage()

  const paymentMethods =
    ((page.props as any)?.paymentMethods as PaymentMethod[]) || []


  const methods = useMemo(() => {
    return paymentMethods
      .filter((method) => method.is_enabled)
      .map((m) => ({
        id: m.id,
        value: m.method,
        label: m.method,
        address: m.address,
        charges: m.charges,
        logo: cryptoLogos[m.method] || btcLogo,
      }))
  }, [paymentMethods])

  const [amount, setAmount] = useState("")
  const [showDropdown, setShowDropdown] = useState(false)
  const [copied, setCopied] = useState(false)

  const [method, setMethod] = useState<any>(methods[0] || null)

  const formatAmount = (value: string) => {
    const numeric = value.replace(/[^0-9.]/g, "")

    if (!numeric) return ""

    const parts = numeric.split(".")

    const integer = parts[0].replace(
      /\B(?=(\d{3})+(?!\d))/g,
      ","
    )

    return parts.length > 1
      ? `${integer}.${parts[1].slice(0, 2)}`
      : integer
  }

  const handleAmountChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setAmount(formatAmount(e.target.value))
  }

  const handleMethodSelect = (selected: any) => {
    setMethod(selected)
    setShowDropdown(false)
    setCopied(false)
  }

  const handleCopy = async () => {
    if (!method?.address) return

    try {
      await navigator.clipboard.writeText(method.address)

      setCopied(true)

      setTimeout(() => {
        setCopied(false)
      }, 2000)
    } catch (error) {
      console.error(error)
    }
  }

  const handleProceed = () => {
    if (!method) return

    const numeric = parseFloat(amount.replace(/,/g, ""))

    if (!amount || isNaN(numeric)) {
      alert("Please enter a valid amount")
      return
    }

    window.location.href = `/dashboard/crypto-checkout?method=${method.value}&amount=${numeric}&wallet=${encodeURIComponent(method.address)}`
  }

  const handleSubmit = () => {
    if (!method) return

    const numeric = parseFloat(amount.replace(/,/g, ""))

    if (!amount || isNaN(numeric)) {
      alert("Please enter a valid amount")
      return
    }

    router.post("/transactions", {
      amount: numeric,
      method: "crypto",
      channel: method.value,
      type: "credit",
      category: "deposit",
      status: "pending",
    })
  }

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modalContent}>
        <button
          className={styles.closeBtn}
          onClick={onClose}
        >
          <MdClose size={22} />
        </button>

        <h2>Deposit Funds To Your Wallet</h2>

        <p>
          To make a deposit, choose your preferred
          payment method and send the entered amount
          to the corresponding wallet address.
        </p>

        {methods.length === 0 ? (
          <div
            style={{
              padding: "1rem",
              borderRadius: "8px",
              background: "#fff3cd",
              color: "#856404",
              marginTop: "1rem",
            }}
          >
            No payment methods are currently available.
          </div>
        ) : (
          <>
            <div className={styles.inputGroup}>
              <label>Crypto Method</label>

              <div
                className={styles.selectWrapper}
                onClick={() =>
                  setShowDropdown(!showDropdown)
                }
              >
                <div className={styles.selectDisplay}>
                  <img
                    src={method?.logo}
                    alt={method?.label}
                  />

                  <span>{method?.label}</span>

                  <FaChevronDown />
                </div>

                {showDropdown && (
                  <div className={styles.dropdown}>
                    {methods.map((m) => (
                      <div
                        key={m.id}
                        className={styles.dropdownItem}
                        onClick={(e) => {
                          e.stopPropagation()
                          handleMethodSelect(m)
                        }}
                      >
                        <img
                          src={m.logo}
                          alt={m.label}
                        />

                        <span>{m.label}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <label>Amount in USD</label>

              <input
                type="text"
                placeholder="Enter amount"
                value={amount}
                onChange={handleAmountChange}
                className={styles.amountInput}
              />
            </div>

            {/* <div className={styles.walletGroup}>
              <label>Wallet Address</label>

              <div className={styles.walletRow}>
                <span className={styles.walletText}>
                  {method?.address}
                </span>

                <button
                  onClick={handleCopy}
                  className={styles.copyBtn}
                >
                  {copied ? "Copied!" : "Copy"}
                </button>
              </div>
            </div> */}

            <small>
              By clicking proceed, you agree to our
              terms and conditions.
            </small>

            <button
              className={styles.proceedBtn}
              onClick={handleProceed}
            >
              Proceed To Checkout
            </button>
          </>
        )}
      </div>
    </div>
  )
}

export default DepositModal