/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from 'react'
import { router, useForm, usePage } from '@inertiajs/react'
import styles from './withdraw.module.scss'
import { MdClose } from 'react-icons/md'
import { FaChevronDown } from 'react-icons/fa'
import { formatMoneyComplete } from '@/lib/utils/format-money'
import currencyData from "../../../../../data/countries-currencies.json";

const withdrawalTypes = [
  { id: 1, value: 'crypto', label: 'Crypto' },
  { id: 2, value: 'bank', label: 'Bank Transfer' },
]

interface WithdrawalModalProps {
  onClose: () => void
}

const WithdrawalModal = ({ onClose }: WithdrawalModalProps) => {
  const [type, setType] = useState(withdrawalTypes[0])
  const [showDropdown, setShowDropdown] = useState(false)
  const [displayAmount, setDisplayAmount] = useState('')

  const { auth, appSettings } = usePage<any>().props

  const user = auth.user

   const currency = currencyData.find(
    (item) => item.currency_code === appSettings?.base_currency
  )

  const { data, setData, post, processing, reset, errors } = useForm({
    user_id: user.id,
    type: 'withdrawal',
    channel: 'crypto',
    amount: '',
    meta: {
      wallet: '',
      accountName: '',
      accountNumber: '',
      bankName: '',
      note: '',
    },
  })

  // Format amount for UI only
  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>) => {
    const raw = e.target.value.replace(/,/g, '')
    setDisplayAmount(formatAmount(e.target.value))
    setData('amount', raw)
  }

  const handleTypeSelect = (item: any) => {
    setType(item)
    setShowDropdown(false)

    setData({
      ...data,
      channel: item.value === 'crypto' ? 'crypto' : 'fiat',
      meta: {
        wallet: '',
        accountName: '',
        accountNumber: '',
        bankName: '',
        note: '',
      },
    })
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    post(route('transactions.store'), {
      onSuccess: () => {
        reset()
        setDisplayAmount('')
        onClose()
        router.reload({ only: ['flash'] })
      },
    })
  }

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

        <h2>Withdraw Funds</h2>
        <p>Select your withdrawal method and enter the required details.</p>

        <form onSubmit={handleSubmit} className={styles.inputGroup}>
          {/* Withdrawal Type */}
          <label>Withdrawal Type</label>
          <div className={styles.selectWrapper} onClick={() => setShowDropdown(!showDropdown)}>
            <div className={styles.selectDisplay}>
              <span>{type.label}</span>
              <FaChevronDown />
            </div>

            {showDropdown && (
              <div className={styles.dropdown}>
                {withdrawalTypes.map((item) => (
                  <div
                    key={item.id}
                    className={styles.dropdownItem}
                    onClick={() => handleTypeSelect(item)}
                  >
                    {item.label}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Crypto */}
          {type.value === 'crypto' && (
            <>
              <label>Wallet Address</label>
              <input
                type="text"
                placeholder="Enter wallet address"
                value={data.meta.wallet}
                onChange={(e) =>
                  setData('meta', { ...data.meta, wallet: e.target.value })
                }
                className={styles.amountInput}
              />
            </>
          )}

          {/* Bank */}
          {type.value === 'bank' && (
            <>
              <label>Account Name</label>
              <input
                type="text"
                value={data.meta.accountName}
                onChange={(e) =>
                  setData('meta', { ...data.meta, accountName: e.target.value })
                }
                className={styles.amountInput}
              />

              <label>Account Number</label>
              <input
                type="text"
                value={data.meta.accountNumber}
                onChange={(e) =>
                  setData('meta', { ...data.meta, accountNumber: e.target.value })
                }
                className={styles.amountInput}
              />

              <label>Bank Name</label>
              <input
                type="text"
                value={data.meta.bankName}
                onChange={(e) =>
                  setData('meta', { ...data.meta, bankName: e.target.value })
                }
                className={styles.amountInput}
              />
            </>
          )}

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

          <div className={styles.notice}>
            <p>
              Withdrawals typically takes 24 hours to process.
              For any delays, contact your account manager.
            </p>
          </div>

          <div className={styles.balanceCard}>
            <div className={styles.balanceCard__content}>
              <span className={styles.balanceCard__label}>
                Available Balance
              </span>

              <h3 className={styles.balanceCard__amount}>
                {currency?.currency_symbol}
                {formatMoneyComplete(auth?.user?.balance ?? 0)}
              </h3>
            </div>
          </div>

          {errors.amount && (
            <span className={styles.error}>
              {errors.amount}
            </span>
          )}

          {!auth?.user?.can_withdraw && (
              <div className={styles.error}>
                Withdrawals are currently disabled for your account.
                Please contact your account manager.
              </div>
            )}

          {auth?.user?.needs_upgrade && (
              <div className={styles.error}>
                You need your account upgraded before you can continue.
                Please contact your account manager
              </div>
            )}

          {/* <button
            type="submit"
            className={styles.proceedBtn}
            disabled={processing}
          >
            {processing ? 'Processing...' : 'Withdraw Now'}
          </button> */}

          <button
            type="submit"
            className={styles.proceedBtn}
            disabled={
              processing ||
              !auth?.user?.can_withdraw
            }
          >
            {processing
              ? "Processing..."
              : "Withdraw Now"}
          </button>
        </form>
      </div>
    </div>
  )
}

export default WithdrawalModal
