import { useState, useEffect } from 'react'
import { numberToWords } from '@persian-tools/persian-tools'
import { Modal } from './ui/modal'
import { apiClient } from '../api/client'
import { DateTimePicker } from './DateTimePicker'
import { CustomerSelector } from './CustomerSelector'
import { persianToEnglish, toEnglishNumeric, toEnglishDigitsOnly, validateCardNumber, validateSheba, CARD_NUMBER_LENGTH, SHEBA_LENGTH } from '../utils/numberUtils'
import { useSettings } from '../context/SettingsContext'
import Label from './form/Label'
import { BALANCE_LABELS, DEBT_CLASSES, CREDIT_CLASSES } from '../constants/balance'

// لیست بانک‌های ایرانی
const IRANIAN_BANKS = [
  { code: 'melli', name: 'بانک ملی ایران' },
  { code: 'mellat', name: 'بانک ملت' },
  { code: 'saderat', name: 'بانک صادرات ایران' },
  { code: 'tejarat', name: 'بانک تجارت' },
  { code: 'sepah', name: 'بانک سپه' },
  { code: 'keshavarzi', name: 'بانک کشاورزی' },
  { code: 'maskan', name: 'بانک مسکن' },
  { code: 'post', name: 'پست بانک ایران' },
  { code: 'tosee', name: 'بانک توسعه تعاون' },
  { code: 'sina', name: 'بانک سینا' },
  { code: 'saman', name: 'بانک سامان' },
  { code: 'parsian', name: 'بانک پارسیان' },
  { code: 'eghtesad', name: 'بانک اقتصاد نوین' },
  { code: 'dey', name: 'بانک دی' },
  { code: 'ansar', name: 'بانک انصار' },
  { code: 'mehr', name: 'بانک مهر اقتصاد' },
  { code: 'karafarin', name: 'بانک کارآفرین' },
  { code: 'pasargad', name: 'بانک پاسارگاد' },
  { code: 'sarmayeh', name: 'بانک سرمایه' },
  { code: 'tosee-saderat', name: 'بانک توسعه صادرات ایران' },
  { code: 'hekmah', name: 'بانک حکمت ایرانیان' },
  { code: 'ayandeh', name: 'بانک آینده' },
  { code: 'gardeshgari', name: 'بانک گردشگری' },
  { code: 'iran-zamin', name: 'بانک ایران زمین' },
  { code: 'other', name: 'سایر' },
]

interface UnbalancedCustomer {
  customer: {
    id: number
    name: string
    code: string
    mobile?: string
  }
  remaining: {
    remaining_debt: number
    remaining_credit: number
  }
}

interface QuickTransactionModalProps {
  isOpen: boolean
  onClose: () => void
  orderId: number
  orderNumber: string
  customerId?: number
  /** BUY = خرید از مشتری → مشتری دریافت‌کننده پول. SELL = فروش به مشتری → مشتری پرداخت‌کننده. */
  orderType?: 'BUY' | 'SELL'
  onSuccess?: () => void
}

const getCurrentDateTimeISO = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

export const QuickTransactionModal = ({
  isOpen,
  onClose,
  orderId,
  orderNumber,
  customerId,
  orderType,
  onSuccess,
}: QuickTransactionModalProps) => {
  const { formatCurrency, getCurrencyLabel } = useSettings()
  const [loading, setLoading] = useState(false)
  const [loadingBalance, setLoadingBalance] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  
  // BUY = خرید از مشتری → مشتری دریافت‌کننده. SELL = فروش به مشتری → مشتری پرداخت‌کننده.
  const [fromCustomerId, setFromCustomerId] = useState<number | null>(orderType === 'SELL' && customerId ? customerId : null)
  const [toCustomerId, setToCustomerId] = useState<number | null>(orderType === 'BUY' && customerId ? customerId : null)
  const [fromBankAccounts, setFromBankAccounts] = useState<any[]>([])
  const [toBankAccounts, setToBankAccounts] = useState<any[]>([])
  const [selectedToBankAccount, setSelectedToBankAccount] = useState<number | null>(null)
  const [amount, setAmount] = useState<string>('')
  const [transactionDate, setTransactionDate] = useState(getCurrentDateTimeISO())
  const [reference, setReference] = useState('')
  const [notes, setNotes] = useState('')
  
  const [remainingMoney, setRemainingMoney] = useState<number>(0)
  const [totalMoney, setTotalMoney] = useState<number>(0)
  const [transactedMoney, setTransactedMoney] = useState<number>(0)
  const [inProgressMoney, setInProgressMoney] = useState<number>(0)
  const [directRemainingMoney, setDirectRemainingMoney] = useState<number>(0)

  // Unbalanced customers
  const [unbalancedCustomers, setUnbalancedCustomers] = useState<UnbalancedCustomer[]>([])
  const [loadingUnbalanced, setLoadingUnbalanced] = useState(false)

  // Quick add bank account modal
  const [showBankAccountModal, setShowBankAccountModal] = useState(false)
  const [newBankAccount, setNewBankAccount] = useState({
    title: '',
    bank_name: '',
    account_number: '',
    card_number: '',
    sheba: '',
  })
  const [savingBankAccount, setSavingBankAccount] = useState(false)
  const [bankAccountModalError, setBankAccountModalError] = useState<string | null>(null)

  useEffect(() => {
    if (isOpen && orderId) {
      loadRemainingBalance()
      loadUnbalancedCustomers()
      // بر اساس نوع سفارش: BUY → مشتری دریافت‌کننده، SELL → مشتری پرداخت‌کننده
      if (customerId) {
        if (orderType === 'BUY') {
          setToCustomerId(customerId)
          setFromCustomerId(null)
        } else if (orderType === 'SELL') {
          setFromCustomerId(customerId)
          setToCustomerId(null)
        } else {
          setFromCustomerId(customerId)
          setToCustomerId(null)
        }
      }
    }
  }, [isOpen, orderId, customerId, orderType])

  const loadUnbalancedCustomers = async () => {
    setLoadingUnbalanced(true)
    try {
      const res = await apiClient.get('/reports/customer-balances', { params: { non_zero: 'true' } })
      const raw = res?.data ?? res
      const data = Array.isArray(raw) ? raw : (raw?.data ?? [])
      setUnbalancedCustomers(Array.isArray(data) ? data : [])
    } catch {
      setUnbalancedCustomers([])
    } finally {
      setLoadingUnbalanced(false)
    }
  }

  const formatAmount = (value: string) => {
    const num = parseFloat(persianToEnglish(value))
    if (isNaN(num)) return ''
    return new Intl.NumberFormat('fa-IR').format(num)
  }

  const toPersianWords = (value: string): string => {
    const num = parseFloat(persianToEnglish(value))
    if (isNaN(num) || num <= 0) return ''
    return numberToWords(Math.floor(num)) + ' ' + getCurrencyLabel()
  }

  const loadRemainingBalance = async () => {
    if (!orderId) return
    setLoadingBalance(true)
    try {
      const res = await apiClient.get(`/orders/${orderId}/remaining-balances`)
      const data = res?.data ?? res
      const remaining = data.money?.remaining_amount ?? 0
      const directRemaining = data.money?.direct_remaining_amount ?? remaining
      const inProgress = data.money?.direct_in_progress_amount ?? 0
      const total = data.money?.total_amount ?? 0
      const transacted = data.money?.transacted_amount ?? 0

      setRemainingMoney(remaining)
      setTotalMoney(total)
      setTransactedMoney(transacted)
      setInProgressMoney(inProgress)
      setDirectRemainingMoney(directRemaining)

      // مبلغ پیشنهادی: فقط ماندهٔ بدون تداخل با تراکنش‌های در حال پردازش تا دوباره ثبت نشود
      const conflictFreeRemaining = Math.max(0, directRemaining - inProgress)
      if (conflictFreeRemaining > 0.01) {
        setAmount(String(Math.floor(conflictFreeRemaining)))
      } else if (inProgress > 0.01 && directRemaining > 0.01) {
        setAmount('') // همهٔ مانده قبلاً در حال پردازش است؛ مبلغ خالی تا تداخلی نشود
      } else if (remaining > 0.01) {
        setAmount(String(Math.floor(remaining)))
      } else if (directRemaining > 0.01) {
        setAmount(String(Math.floor(directRemaining)))
      }
    } catch {
      // Ignore errors
    } finally {
      setLoadingBalance(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setSuccess(null)

    if (!fromCustomerId || !toCustomerId) {
      setError('لطفا پرداخت‌کننده و دریافت‌کننده را انتخاب کنید')
      return
    }

    if (fromCustomerId === toCustomerId) {
      setError('پرداخت‌کننده و دریافت‌کننده نمی‌توانند یکی باشند')
      return
    }

    if (!amount || parseFloat(amount) <= 0) {
      setError('لطفا مبلغ معتبر وارد کنید')
      return
    }

    setLoading(true)
    try {
      const payload: any = {
        from_customer_id: fromCustomerId,
        to_customer_id: toCustomerId,
        amount: parseFloat(persianToEnglish(amount)),
        transaction_date: transactionDate,
        method: 'TRANSFER',
        reference: reference || null,
        notes: notes || null,
        order_id: orderId,
      }

      // Add bank account if selected
      if (selectedToBankAccount !== null && toBankAccounts[selectedToBankAccount]) {
        payload.to_bank_account = toBankAccounts[selectedToBankAccount]
      }

      await apiClient.post('/transactions', payload)
      setSuccess('تراکنش با موفقیت ثبت شد')
      
      setTimeout(() => {
        onSuccess?.()
        handleClose()
      }, 1000)
    } catch (err: any) {
      const msg = err.response?.data?.message || 'خطا در ثبت تراکنش'
      const validationErrors = err.response?.data?.errors
      const fullMsg = validationErrors
        ? `${msg}: ${Object.values(validationErrors).flat().join('، ')}`
        : msg
      setError(fullMsg)
    } finally {
      setLoading(false)
    }
  }

  const openBankAccountModal = () => {
    setBankAccountModalError(null)
    setShowBankAccountModal(true)
  }

  const handleSaveBankAccount = async () => {
    if (!newBankAccount.card_number && !newBankAccount.account_number && !newBankAccount.sheba) {
      return
    }
    if (newBankAccount.card_number && !validateCardNumber(newBankAccount.card_number)) {
      setBankAccountModalError('شماره کارت باید ۱۶ رقم و مطابق استاندارد بانکی باشد.')
      return
    }
    if (newBankAccount.sheba && !validateSheba(newBankAccount.sheba)) {
      setBankAccountModalError('شبا باید ۲۴ رقم (با یا بدون پیش‌وند IR) و معتبر باشد.')
      return
    }
    setBankAccountModalError(null)

    if (!toCustomerId) return

    setSavingBankAccount(true)
    try {
      // Get current customer data
      const customerRes = await apiClient.get(`/customers/${toCustomerId}`)
      const customerData = customerRes.data?.data ?? customerRes.data
      const currentAccounts = customerData.bank_accounts || []
      
      // Add new account
      const updatedAccounts = [...currentAccounts, newBankAccount]
      
      // Update customer
      await apiClient.put(`/customers/${toCustomerId}`, {
        bank_accounts: updatedAccounts,
      })
      
      // Update local state
      setToBankAccounts(updatedAccounts)
      // Auto-select the new account
      setSelectedToBankAccount(updatedAccounts.length - 1)
      
      // Close modal and reset
      setShowBankAccountModal(false)
      setNewBankAccount({
        title: '',
        bank_name: '',
        account_number: '',
        card_number: '',
        sheba: '',
      })
    } catch (err: any) {
      const msg = err.response?.data?.message || 'خطا در ذخیره حساب بانکی'
      setBankAccountModalError(msg)
    } finally {
      setSavingBankAccount(false)
    }
  }

  const handleClose = () => {
    setError(null)
    setSuccess(null)
    setAmount('')
    setReference('')
    setNotes('')
    setToCustomerId(null)
    setFromBankAccounts([])
    setToBankAccounts([])
    setSelectedToBankAccount(null)
    setShowBankAccountModal(false)
    setNewBankAccount({
      title: '',
      bank_name: '',
      account_number: '',
      card_number: '',
      sheba: '',
    })
    setBankAccountModalError(null)
    setRemainingMoney(0)
    setTotalMoney(0)
    setTransactedMoney(0)
    setInProgressMoney(0)
    setDirectRemainingMoney(0)
    onClose()
  }

  return (
    <Modal isOpen={isOpen} onClose={handleClose} className="max-w-2xl m-4">
      <div className="relative w-full p-6 overflow-y-auto bg-white rounded-3xl dark:bg-gray-900">
        <div className="mb-6">
          <h3 className="text-xl font-semibold text-gray-800 dark:text-white/90">
            ثبت سریع تراکنش مالی
          </h3>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            سفارش: {orderNumber}
          </p>
          {remainingMoney > 0.01 && totalMoney > 0 && (
            <div className="mt-3 p-3 rounded-lg bg-amber-50 border border-amber-200 dark:bg-amber-500/10 dark:border-amber-500/20 space-y-1.5">
              <p className="text-sm text-amber-800 dark:text-amber-300">
                <span className="font-medium">مانده:</span> {formatCurrency(remainingMoney)} {getCurrencyLabel()}
                <span className="mx-2 text-amber-600 dark:text-amber-400">•</span>
                <span className="font-medium">کل:</span> {formatCurrency(totalMoney)} {getCurrencyLabel()}
                <span className="mx-2 text-amber-600 dark:text-amber-400">•</span>
                <span className="font-medium">{((transactedMoney / totalMoney) * 100).toLocaleString('fa-IR', { maximumFractionDigits: 1 })}%</span> تسویه شده
              </p>
              {inProgressMoney > 0.01 && (
                <p className="text-sm text-amber-800 dark:text-amber-300 flex items-center gap-1.5 flex-wrap">
                  <span className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 bg-amber-200/60 dark:bg-amber-500/20 font-medium">
                    در حال پردازش (پیش‌نویس/در انتظار تسویه):
                  </span>
                  <span className="font-semibold">{formatCurrency(inProgressMoney)} {getCurrencyLabel()}</span>
                  {directRemainingMoney - inProgressMoney > 0.01 && (
                    <>
                      <span className="text-amber-600 dark:text-amber-400">•</span>
                      <span>مانده قابل ثبت بدون تداخل: <strong>{formatCurrency(Math.max(0, directRemainingMoney - inProgressMoney))} {getCurrencyLabel()}</strong></span>
                    </>
                  )}
                </p>
              )}
            </div>
          )}
        </div>

        {error && (
          <div className="mb-4 rounded-lg border border-error-200 bg-error-50 p-4 dark:border-error-500/20 dark:bg-error-500/10">
            <p className="text-sm text-error-600 dark:text-error-400">{error}</p>
          </div>
        )}
        {success && (
          <div className="mb-4 rounded-lg border border-success-200 bg-success-50 p-4 dark:border-success-500/20 dark:bg-success-500/10">
            <p className="text-sm text-success-600 dark:text-success-400">{success}</p>
          </div>
        )}

        {/* Unbalanced Customers Quick Select */}
        <div className="mb-4 grid grid-cols-1 gap-4 lg:grid-cols-2">
          {/* باکس مشتریان بدهکار */}
          <div className="rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div className="border-b border-gray-200 px-4 py-3 dark:border-gray-800">
              <div className="flex items-center gap-2">
                <svg className={`w-4 h-4 ${DEBT_CLASSES.icon}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <h3 className="text-xs font-medium text-gray-800 dark:text-white/90">{BALANCE_LABELS.customersDebtor} (به ما بدهکار)</h3>
                <span className="text-xs text-gray-500 dark:text-gray-400">
                  ({unbalancedCustomers.filter((i) => i.remaining.remaining_debt > 0.01).length})
                </span>
              </div>
            </div>
            {loadingUnbalanced ? (
              <div className="flex items-center justify-center py-4">
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-error-500 border-t-transparent"></div>
              </div>
            ) : unbalancedCustomers.filter((i) => i.remaining.remaining_debt > 0.01).length === 0 ? (
              <div className="py-4 text-center text-xs text-gray-500 dark:text-gray-400">
                {BALANCE_LABELS.noDebt}
              </div>
            ) : (
              <div className="max-h-48 overflow-y-auto">
                <div className="divide-y divide-gray-100 dark:divide-gray-800">
                  {unbalancedCustomers
                    .filter((item) => item.remaining.remaining_debt > 0.01)
                    .map((item) => {
                      const debtAmount = item.remaining.remaining_debt
                      const isSelectedFrom = fromCustomerId === item.customer.id
                      return (
                        <div
                          key={item.customer.id}
                          className={`p-2 hover:bg-gray-50 dark:hover:bg-white/[0.02] ${isSelectedFrom ? 'bg-brand-50 dark:bg-brand-500/10' : ''}`}
                        >
                          <div className="flex items-center justify-between gap-2">
                            <div className="flex-1 min-w-0">
                              <p className="text-xs font-medium text-gray-800 dark:text-white/90 truncate">{item.customer.name}</p>
                              {item.customer.mobile && (
                                <p className="text-xs text-gray-500 dark:text-gray-400">{item.customer.mobile}</p>
                              )}
                              <p className={`text-xs font-medium ${DEBT_CLASSES.text} mt-1`}>
                                {new Intl.NumberFormat('fa-IR').format(debtAmount)} {getCurrencyLabel()}
                              </p>
                            </div>
                            <button
                              type="button"
                              onClick={() => {
                                setFromCustomerId(item.customer.id)
                                setAmount(String(Math.floor(debtAmount)))
                              }}
                              className={`shrink-0 rounded px-2 py-1 text-xs font-medium transition ${
                                isSelectedFrom
                                  ? DEBT_CLASSES.buttonActive
                                  : DEBT_CLASSES.button
                              }`}
                              title="انتخاب به عنوان پرداخت‌کننده"
                            >
                              انتخاب
                            </button>
                          </div>
                        </div>
                      )
                    })}
                </div>
              </div>
            )}
          </div>

          {/* باکس مشتریان بستانکار */}
          <div className="rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div className="border-b border-gray-200 px-4 py-3 dark:border-gray-800">
              <div className="flex items-center gap-2">
                <svg className={`w-4 h-4 ${CREDIT_CLASSES.icon}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <h3 className="text-xs font-medium text-gray-800 dark:text-white/90">{BALANCE_LABELS.customersCreditor} (از ما بستانکار)</h3>
                <span className="text-xs text-gray-500 dark:text-gray-400">
                  ({unbalancedCustomers.filter((i) => i.remaining.remaining_credit > 0.01).length})
                </span>
              </div>
            </div>
            {loadingUnbalanced ? (
              <div className="flex items-center justify-center py-4">
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-success-500 border-t-transparent"></div>
              </div>
            ) : unbalancedCustomers.filter((i) => i.remaining.remaining_credit > 0.01).length === 0 ? (
              <div className="py-4 text-center text-xs text-gray-500 dark:text-gray-400">
                {BALANCE_LABELS.noCredit}
              </div>
            ) : (
              <div className="max-h-48 overflow-y-auto">
                <div className="divide-y divide-gray-100 dark:divide-gray-800">
                  {unbalancedCustomers
                    .filter((item) => item.remaining.remaining_credit > 0.01)
                    .map((item) => {
                      const creditAmount = item.remaining.remaining_credit
                      const isSelectedTo = toCustomerId === item.customer.id
                      return (
                        <div
                          key={item.customer.id}
                          className={`p-2 hover:bg-gray-50 dark:hover:bg-white/[0.02] ${isSelectedTo ? 'bg-brand-50 dark:bg-brand-500/10' : ''}`}
                        >
                          <div className="flex items-center justify-between gap-2">
                            <div className="flex-1 min-w-0">
                              <p className="text-xs font-medium text-gray-800 dark:text-white/90 truncate">{item.customer.name}</p>
                              {item.customer.mobile && (
                                <p className="text-xs text-gray-500 dark:text-gray-400">{item.customer.mobile}</p>
                              )}
                              <p className={`text-xs font-medium ${CREDIT_CLASSES.text} mt-1`}>
                                {new Intl.NumberFormat('fa-IR').format(creditAmount)} {getCurrencyLabel()}
                              </p>
                            </div>
                            <button
                              type="button"
                              onClick={() => {
                                setToCustomerId(item.customer.id)
                                setAmount(String(Math.floor(creditAmount)))
                              }}
                              className={`shrink-0 rounded px-2 py-1 text-xs font-medium transition ${
                                isSelectedTo
                                  ? CREDIT_CLASSES.buttonActive
                                  : CREDIT_CLASSES.button
                              }`}
                              title="انتخاب به عنوان دریافت‌کننده"
                            >
                              انتخاب
                            </button>
                          </div>
                        </div>
                      )
                    })}
                </div>
              </div>
            )}
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
              <Label>پرداخت‌کننده *</Label>
              <CustomerSelector
                value={fromCustomerId}
                onChange={(id, _name, bankAccounts) => {
                  setFromCustomerId(id)
                  setFromBankAccounts(bankAccounts || [])
                }}
                required
              />
            </div>

            <div>
              <Label>دریافت‌کننده *</Label>
              <CustomerSelector
                value={toCustomerId}
                onChange={(id, _name, bankAccounts) => {
                  setToCustomerId(id)
                  setToBankAccounts(bankAccounts || [])
                  setSelectedToBankAccount(bankAccounts && bankAccounts.length > 0 ? 0 : null)
                }}
                required
              />
              {toCustomerId && (
                <div className="mt-3">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-gray-600 dark:text-gray-400">
                      حساب بانکی مقصد {toBankAccounts.length > 0 ? '(انتخاب کنید)' : ''}:
                    </p>
                    <button
                      type="button"
                      onClick={openBankAccountModal}
                      className="text-xs text-brand-600 hover:text-brand-700 dark:text-brand-400 flex items-center gap-1"
                    >
                      <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                      </svg>
                      افزودن حساب
                    </button>
                  </div>
                  {toBankAccounts.length > 0 ? (
                    <div className="space-y-2">
                    {toBankAccounts.map((acc: any, idx: number) => (
                      <label
                        key={idx}
                        className={`flex items-start gap-3 p-2 rounded-lg border cursor-pointer transition-all ${
                          selectedToBankAccount === idx
                            ? 'border-brand-500 bg-brand-50 dark:border-brand-400 dark:bg-brand-500/10'
                            : 'border-gray-200 bg-gray-50 hover:border-gray-300 dark:border-gray-700 dark:bg-gray-800 dark:hover:border-gray-600'
                        }`}
                      >
                        <input
                          type="radio"
                          name="toBankAccount"
                          checked={selectedToBankAccount === idx}
                          onChange={() => setSelectedToBankAccount(idx)}
                          className="mt-1 h-4 w-4 text-brand-600 focus:ring-brand-500"
                        />
                        <div className="flex-1 min-w-0 text-xs">
                          <div className="font-medium text-gray-800 dark:text-white/90">
                            {acc.title || acc.bank_name || `حساب ${idx + 1}`}
                          </div>
                          {acc.card_number && (
                            <div className="text-gray-600 dark:text-gray-400 font-mono" dir="ltr">
                              کارت: {(acc.card_number.match(/.{1,4}/g) ?? []).join('-')}
                            </div>
                          )}
                          {acc.account_number && (
                            <div className="text-gray-600 dark:text-gray-400 font-mono" dir="ltr">
                              شماره حساب: {acc.account_number}
                            </div>
                          )}
                          {acc.sheba && (
                            <div className="text-gray-600 dark:text-gray-400 font-mono" dir="ltr">
                              شبا: IR{acc.sheba}
                            </div>
                          )}
                        </div>
                      </label>
                    ))}
                    </div>
                  ) : (
                    <div className="rounded-lg border border-dashed border-gray-300 p-3 text-center dark:border-gray-700">
                      <p className="text-xs text-gray-500 dark:text-gray-400">حساب بانکی ثبت نشده</p>
                    </div>
                  )}
                </div>
              )}
            </div>

            <div>
              <Label>مبلغ ({getCurrencyLabel()}) *</Label>
              <div className="mt-2">
                <input
                  type="text"
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  value={amount}
                  onChange={(e) => setAmount(toEnglishNumeric(e.target.value))}
                  placeholder="مثلا 5000000"
                  required
                />
                {amount && (
                  <div className="mt-1 space-y-0.5">
                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      {formatAmount(amount)} {getCurrencyLabel()}
                    </div>
                    {toPersianWords(amount) && (
                      <div className="text-xs text-brand-500 dark:text-brand-400">
                        {toPersianWords(amount)}
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            <div>
              <Label>تاریخ و ساعت تراکنش *</Label>
              <DateTimePicker
                value={transactionDate}
                onChange={setTransactionDate}
                placeholder="تاریخ و ساعت تراکنش را انتخاب کنید"
                required
              />
            </div>

            <div>
              <Label>شماره پیگیری / مرجع</Label>
              <input
                type="text"
                className="mt-2 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                value={reference}
                onChange={(e) => setReference(e.target.value)}
                placeholder="شماره پیگیری یا مرجع"
              />
            </div>
          </div>

          <div>
            <Label>توضیحات</Label>
            <textarea
              className="mt-2 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={2}
              placeholder="توضیحات اختیاری..."
            />
          </div>

          <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-800">
            <button
              type="button"
              onClick={handleClose}
              className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-5 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
            >
              انصراف
            </button>
            <button
              type="submit"
              disabled={loading}
              className="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {loading ? (
                <>
                  <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  در حال ثبت...
                </>
              ) : (
                'ثبت تراکنش'
              )}
            </button>
          </div>
        </form>
      </div>

      {/* Bank Account Modal */}
      {showBankAccountModal && (
        <div className="fixed inset-0 z-[999999] flex items-center justify-center bg-black/50" onClick={() => setShowBankAccountModal(false)}>
          <div className="mx-4 w-full max-w-md rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900" onClick={(e) => e.stopPropagation()}>
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">
                افزودن حساب بانکی
              </h3>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                حساب جدید برای دریافت‌کننده
              </p>
            </div>
            {bankAccountModalError && (
              <div className="mb-4 rounded-lg border border-error-200 bg-error-50 px-4 py-3 text-sm text-error-700 dark:border-error-500/20 dark:bg-error-500/10 dark:text-error-400">
                {bankAccountModalError}
              </div>
            )}
            <div className="space-y-4">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                  عنوان حساب
                </label>
                <input
                  type="text"
                  placeholder="مثلا: حساب اصلی"
                  value={newBankAccount.title}
                  onChange={(e) => setNewBankAccount({ ...newBankAccount, title: e.target.value })}
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                />
              </div>

              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                  نام بانک
                </label>
                <select
                  value={newBankAccount.bank_name}
                  onChange={(e) => setNewBankAccount({ ...newBankAccount, bank_name: e.target.value })}
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                >
                  <option value="">انتخاب بانک...</option>
                  {IRANIAN_BANKS.map((bank) => (
                    <option key={bank.code} value={bank.name}>
                      {bank.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                  شماره کارت
                </label>
                <input
                  type="text"
                  placeholder="xxxx-xxxx-xxxx-xxxx"
                  value={newBankAccount.card_number ? (newBankAccount.card_number.match(/.{1,4}/g) ?? []).join('-') : ''}
                  onChange={(e) => {
                    setBankAccountModalError(null)
                    setNewBankAccount({ ...newBankAccount, card_number: toEnglishDigitsOnly(e.target.value).slice(0, CARD_NUMBER_LENGTH) })
                  }}
                  maxLength={19}
                  dir="ltr"
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                />
              </div>

              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                  شبا (IBAN)
                </label>
                <input
                  type="text"
                  placeholder="IRxxxxxxxxxxxxxxxxxxxxxxxx"
                  value={newBankAccount.sheba ? `IR${newBankAccount.sheba}` : ''}
                  onChange={(e) => {
                    setBankAccountModalError(null)
                    const value = e.target.value.replace(/^IR/i, '')
                    setNewBankAccount({ ...newBankAccount, sheba: toEnglishDigitsOnly(value).slice(0, SHEBA_LENGTH) })
                  }}
                  maxLength={26}
                  dir="ltr"
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                />
              </div>

              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                  شماره حساب
                </label>
                <input
                  type="text"
                  placeholder="شماره حساب"
                  value={newBankAccount.account_number}
                  onChange={(e) => setNewBankAccount({ ...newBankAccount, account_number: toEnglishDigitsOnly(e.target.value) })}
                  dir="ltr"
                  className="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                />
              </div>
            </div>

            <div className="mt-6 flex items-center justify-end gap-3 border-t border-gray-200 pt-4 dark:border-gray-700">
              <button
                type="button"
                onClick={() => {
                  setShowBankAccountModal(false)
                  setBankAccountModalError(null)
                  setNewBankAccount({ title: '', bank_name: '', account_number: '', card_number: '', sheba: '' })
                }}
                className="rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 shadow-theme-xs hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
              >
                انصراف
              </button>
              <button
                type="button"
                onClick={handleSaveBankAccount}
                disabled={savingBankAccount || (!newBankAccount.card_number && !newBankAccount.account_number && !newBankAccount.sheba)}
                className="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-theme-xs hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {savingBankAccount ? (
                  <>
                    <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                    در حال ذخیره...
                  </>
                ) : (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                    ذخیره حساب
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </Modal>
  )
}
