import { useEffect, useState, useRef } from 'react'
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { numberToWords } from '@persian-tools/persian-tools'
import { apiClient } from '../../api/client'
import { DateTimePicker } from '../../components/DateTimePicker'
import { CustomerSelector } from '../../components/CustomerSelector'
import {
  persianToEnglish,
  toEnglishDigitsOnly,
  toEnglishNumeric,
  validateCardNumber,
  validateSheba,
  CARD_NUMBER_LENGTH,
  SHEBA_LENGTH,
} from '../../utils/numberUtils'
import { useSettings } from '../../context/SettingsContext'
import PageMeta from '../../components/common/PageMeta'
import PageBreadcrumb from '../../components/common/PageBreadCrumb'
import Label from '../../components/form/Label'
import Badge from '../../components/ui/badge/Badge'
import axios from 'axios'
import { BALANCE_LABELS, DEBT_CLASSES, CREDIT_CLASSES } from '../../constants/balance'

// لیست بانک‌های ایرانی
const IRANIAN_BANKS = [
  { code: 'melli', name: 'بانک ملی ایران' },
  { code: 'sepah', name: 'بانک سپه' },
  { code: 'tosee_taavon', name: 'بانک توسعه تعاون' },
  { code: 'post', name: 'پست بانک ایران' },
  { code: 'tosee_saderat', name: 'بانک توسعه صادرات' },
  { code: 'sanat_madan', name: 'بانک صنعت و معدن' },
  { code: 'keshavarzi', name: 'بانک کشاورزی' },
  { code: 'maskan', name: 'بانک مسکن' },
  { code: 'eghtesad_novin', name: 'بانک اقتصاد نوین' },
  { code: 'parsian', name: 'بانک پارسیان' },
  { code: 'pasargad', name: 'بانک پاسارگاد' },
  { code: 'karafarin', name: 'بانک کارآفرین' },
  { code: 'saman', name: 'بانک سامان' },
  { code: 'sina', name: 'بانک سینا' },
  { code: 'sarmaye', name: 'بانک سرمایه' },
  { code: 'tat', name: 'بانک تات' },
  { code: 'shahr', name: 'بانک شهر' },
  { code: 'dey', name: 'بانک دی' },
  { code: 'saderat', name: 'بانک صادرات ایران' },
  { code: 'mellat', name: 'بانک ملت' },
  { code: 'tejarat', name: 'بانک تجارت' },
  { code: 'refah', name: 'بانک رفاه کارگران' },
  { code: 'ansar', name: 'بانک انصار' },
  { code: 'hekmat', name: 'بانک حکمت ایرانیان' },
  { code: 'gardeshgari', name: 'بانک گردشگری' },
  { code: 'ayandeh', name: 'بانک آینده' },
  { code: 'khavarmianeh', name: 'بانک خاورمیانه' },
  { code: 'iran_zamin', name: 'بانک ایران زمین' },
  { code: 'qavamin', name: 'بانک قوامین' },
  { code: 'kosar', name: 'موسسه کوثر' },
  { code: 'melal', name: 'موسسه ملل' },
  { code: 'resalat', name: 'بانک رسالت' },
  { code: 'mehr_iran', name: 'بانک مهر ایران' },
  { code: 'noor', name: 'موسسه نور' },
  { code: 'central', name: 'بانک مرکزی' },
  { code: 'other', name: 'سایر' },
]

// Get current datetime in ISO format for default value
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}`
}

// فقط انتقال بانکی؛ حساب انتخاب‌شده در بخش دریافت‌کننده مشخص می‌شود
const methodOptions = [
  { value: 'TRANSFER', label: 'انتقال بانکی' },
]

const getStatusBadge = (status: string) => {
  const statusMap: Record<string, { color: 'primary' | 'success' | 'error' | 'warning' | 'light', label: string }> = {
    'DRAFT': { color: 'light', label: 'پیش‌نویس' },
    'SUBMITTED': { color: 'warning', label: 'ارسال شده' },
    'SETTLED': { color: 'success', label: 'تسویه شده' },
    }
  const config = statusMap[status] || { color: 'light' as const, label: status }
  return <Badge color={config.color} variant="light" size="sm">{config.label}</Badge>
}

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

export const TransactionFormPage = () => {
  const navigate = useNavigate()
  const { id } = useParams<{ id: string }>()
  const [searchParams] = useSearchParams()
  const customerId = searchParams.get('customer_id')
  const orderIdFromQuery = searchParams.get('order_id') || ''
  const isEdit = !!id
  const { getCurrencyLabel } = useSettings()

  const [loading, setLoading] = useState(false)
  const [loadingData, setLoadingData] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  // Form state - Customer based (no accounts needed)
  const [fromCustomerId, setFromCustomerId] = useState<number | null>(null)
  const [toCustomerId, setToCustomerId] = useState<number | null>(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 [method, setMethod] = useState('TRANSFER')
  const [reference, setReference] = useState('')
  const [notes, setNotes] = useState('')
  
  // Transaction data for edit mode
  const [transaction, setTransaction] = useState<any>(null)
  /** سفارش مرتبط (برای لینک تراکنش به سفارش) - در ایجاد و ویرایش */
  const [orderIdForEdit, setOrderIdForEdit] = useState<number | null>(null)
  /** لیست سفارشات برای انتخاب (سفارشات پرداخت‌کننده + دریافت‌کننده) */
  const [ordersForLink, setOrdersForLink] = useState<{ id: number; order_number: string; order_type: string; label?: string }[]>([])
  const [loadingOrdersForLink, setLoadingOrdersForLink] = useState(false)
  
  // Quick add bank account modal
  const [showBankAccountModal, setShowBankAccountModal] = useState(false)
  const [bankAccountModalFor, setBankAccountModalFor] = useState<'from' | 'to'>('to')
  const [newBankAccount, setNewBankAccount] = useState({
    title: '',
    bank_name: '',
    account_number: '',
    card_number: '',
    sheba: '',
  })
  const [savingBankAccount, setSavingBankAccount] = useState(false)
  const [bankAccountModalError, setBankAccountModalError] = useState<string | null>(null)

  // Unbalanced customers
  const [unbalancedCustomers, setUnbalancedCustomers] = useState<UnbalancedCustomer[]>([])
  const [loadingUnbalanced, setLoadingUnbalanced] = useState(false)
  
  // Attachment upload
  const [attachmentUrl, setAttachmentUrl] = useState<string | null>(null)
  const [uploadingAttachment, setUploadingAttachment] = useState(false)
  const [attachmentError, setAttachmentError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  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 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)

    const customerId = bankAccountModalFor === 'from' ? fromCustomerId : toCustomerId
    if (!customerId) return

    setSavingBankAccount(true)
    try {
      // Get current customer data
      const customerRes = await apiClient.get(`/customers/${customerId}`)
      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/${customerId}`, {
        bank_accounts: updatedAccounts,
      })
      
      // Update local state
      if (bankAccountModalFor === 'from') {
        setFromBankAccounts(updatedAccounts)
      } else {
        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) {
      console.error('Error saving bank account:', err)
    } finally {
      setSavingBankAccount(false)
    }
  }

  const openBankAccountModal = (forCustomer: 'from' | 'to') => {
    setBankAccountModalError(null)
    setBankAccountModalFor(forCustomer)
    setShowBankAccountModal(true)
  }

  const handleDeleteToBankAccount = async (accountIndex: number) => {
    if (!toCustomerId || !confirm('آیا از حذف این حساب بانکی اطمینان دارید؟')) return
    try {
      const customerRes = await apiClient.get(`/customers/${toCustomerId}`)
      const customerData = customerRes.data?.data ?? customerRes.data
      const currentAccounts = customerData.bank_accounts || []
      const updatedAccounts = currentAccounts.filter((_: any, i: number) => i !== accountIndex)
      await apiClient.put(`/customers/${toCustomerId}`, { bank_accounts: updatedAccounts })
      setToBankAccounts(updatedAccounts)
      if (selectedToBankAccount === accountIndex) {
        setSelectedToBankAccount(updatedAccounts.length > 0 ? 0 : null)
      } else if (selectedToBankAccount !== null && selectedToBankAccount > accountIndex) {
        setSelectedToBankAccount(selectedToBankAccount - 1)
      }
    } catch (err) {
      console.error('Error deleting bank account:', err)
    }
  }

  const handleDeleteFromBankAccount = async (accountIndex: number) => {
    if (!fromCustomerId || !confirm('آیا از حذف این حساب بانکی اطمینان دارید؟')) return
    try {
      const customerRes = await apiClient.get(`/customers/${fromCustomerId}`)
      const customerData = customerRes.data?.data ?? customerRes.data
      const currentAccounts = customerData.bank_accounts || []
      const updatedAccounts = currentAccounts.filter((_: any, i: number) => i !== accountIndex)
      await apiClient.put(`/customers/${fromCustomerId}`, { bank_accounts: updatedAccounts })
      setFromBankAccounts(updatedAccounts)
    } catch (err) {
      console.error('Error deleting bank account:', err)
    }
  }

  useEffect(() => {
    if (customerId) {
      setFromCustomerId(parseInt(customerId))
    }
    if (isEdit && id) {
      loadTransaction(id)
    } else {
      if (orderIdFromQuery) {
        apiClient.get(`/orders/${orderIdFromQuery}`).then((res) => {
          const order = res?.data?.data ?? res?.data
          if (order?.user_id) {
            if (order.order_type === 'SELL') {
              setFromCustomerId(order.user_id)
            } else {
              setToCustomerId(order.user_id)
            }
            setOrderIdForEdit(parseInt(orderIdFromQuery, 10))
          }
        }).catch(() => {})
      }
      loadUnbalancedCustomers()
    }
  }, [customerId, orderIdFromQuery, id])

  // بارگذاری سفارشات پرداخت‌کننده و دریافت‌کننده برای انتخاب «سفارش مرتبط» (مثل فرم تراکنش فلز)
  useEffect(() => {
    const fromId = fromCustomerId ?? undefined
    const toId = toCustomerId ?? undefined
    if (!fromId && !toId) {
      setOrdersForLink([])
      return
    }
    let cancelled = false
    setLoadingOrdersForLink(true)
    const load = async () => {
      try {
        const promises: Promise<Array<{ id: number; order_number: string; order_type: string }>>[] = []
        if (fromId) {
          promises.push(
            apiClient.get('/orders', { params: { customer_id: fromId, per_page: 100 } }).then((res) => {
              const raw = res?.data ?? res
              const list = raw?.data ?? raw
              const arr = Array.isArray(list) ? list : []
              return arr.map((o: { id: number; order_number: string; order_type: string }) => ({
                ...o,
                label: `${o.order_number} (${o.order_type === 'BUY' ? 'خرید' : 'فروش'}) — پرداخت‌کننده`,
              }))
            })
          )
        }
        if (toId) {
          promises.push(
            apiClient.get('/orders', { params: { customer_id: toId, per_page: 100 } }).then((res) => {
              const raw = res?.data ?? res
              const list = raw?.data ?? raw
              const arr = Array.isArray(list) ? list : []
              return arr.map((o: { id: number; order_number: string; order_type: string }) => ({
                ...o,
                label: `${o.order_number} (${o.order_type === 'BUY' ? 'خرید' : 'فروش'}) — دریافت‌کننده`,
              }))
            })
          )
        }
        const results = await Promise.all(promises)
        const merged = (results.flat() as { id: number; order_number: string; order_type: string; label?: string }[])
        if (!cancelled) setOrdersForLink(merged)
      } catch {
        if (!cancelled) setOrdersForLink([])
      } finally {
        if (!cancelled) setLoadingOrdersForLink(false)
      }
    }
    load()
    return () => { cancelled = true }
  }, [fromCustomerId, toCustomerId])

  // اگر سفارش لینک‌شده در لیست نبود (مثلاً در حالت ویرایش)، آن را جدا بارگذاری کن تا در dropdown نمایش داده شود
  useEffect(() => {
    if (!orderIdForEdit || ordersForLink.some((o) => o.id === orderIdForEdit)) return
    let cancelled = false
    apiClient.get(`/orders/${orderIdForEdit}`).then((res) => {
      const o = res?.data?.data ?? res?.data
      if (!cancelled && o?.id) {
        setOrdersForLink((prev) => {
          if (prev.some((x) => x.id === o.id)) return prev
          return [
            ...prev,
            {
              id: o.id,
              order_number: o.order_number ?? String(o.id),
              order_type: o.order_type ?? '',
              label: `${o.order_number ?? o.id} (${o.order_type === 'BUY' ? 'خرید' : 'فروش'})`,
            },
          ]
        })
      }
    }).catch(() => {})
    return () => { cancelled = true }
  }, [orderIdForEdit, ordersForLink.length])

  const loadTransaction = async (txId: string) => {
    setLoadingData(true)
    try {
      const res = await apiClient.get(`/transactions/${txId}`)
      const data = res?.data ?? res
      setTransaction(data)
      
      // Set customer IDs
      if (data.from_customer_id) {
        setFromCustomerId(data.from_customer_id)
      }
      if (data.to_customer_id) {
        setToCustomerId(data.to_customer_id)
      }
      
      setAmount(String(data.amount))
      setTransactionDate(data.transaction_date)
      setMethod('TRANSFER')
      setReference(data.reference || '')
      setNotes(data.notes || '')
      setOrderIdForEdit(orderIdFromQuery ? parseInt(orderIdFromQuery, 10) : (data.order_id ?? null))
      
      // Fetch signed URL if attachment exists
      if (data.attachment) {
        try {
          const attachmentRes = await apiClient.get(`/transactions/${id}/attachment-url`)
          const attachmentData = attachmentRes.data?.data ?? attachmentRes.data
          setAttachmentUrl(attachmentData.url)
        } catch {
          setAttachmentUrl(null)
        }
      } else {
        setAttachmentUrl(null)
      }
    } catch (err: any) {
      setError('خطا در بارگذاری تراکنش')
    } finally {
      setLoadingData(false)
    }
  }

  const handleAttachmentUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file || !id) return

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf']
    if (!allowedTypes.includes(file.type)) {
      setAttachmentError('فقط فایل‌های JPG، PNG و PDF مجاز هستند')
      return
    }

    // Validate file size (2MB)
    if (file.size > 2 * 1024 * 1024) {
      setAttachmentError('حداکثر حجم فایل ۲ مگابایت است')
      return
    }

    setUploadingAttachment(true)
    setAttachmentError(null)

    try {
      const formData = new FormData()
      formData.append('attachment', file)

      const token = localStorage.getItem('auth_token')
      const baseUrl = import.meta.env.VITE_API_URL ?? '/api'
      
      await axios.post(`${baseUrl}/transactions/${id}/upload`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`,
        },
      })

      // Reload transaction to get updated data
      await loadTransaction(id)
      setSuccess('تصویر فیش با موفقیت آپلود شد')
    } catch (err: any) {
      setAttachmentError(err.response?.data?.message || 'خطا در آپلود فایل')
    } finally {
      setUploadingAttachment(false)
      // Reset file input
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  const handleDeleteAttachment = async () => {
    if (!id || !confirm('آیا از حذف تصویر فیش اطمینان دارید؟')) return

    setUploadingAttachment(true)
    try {
      await apiClient.delete(`/transactions/${id}/attachment`)
      setAttachmentUrl(null)
      setTransaction((prev: any) => prev ? { ...prev, attachment: null } : null)
      setSuccess('تصویر فیش با موفقیت حذف شد')
    } catch (err: any) {
      setAttachmentError(err.response?.data?.message || 'خطا در حذف فایل')
    } finally {
      setUploadingAttachment(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: Record<string, unknown> = {
        from_customer_id: fromCustomerId,
        to_customer_id: toCustomerId,
        amount: parseFloat(persianToEnglish(amount)),
        transaction_date: transactionDate,
        method,
        reference: reference || null,
        notes: notes || null,
      }
      // اتصال به سفارش: در ایجاد از URL یا از انتخاب «سفارش مرتبط»، در ویرایش از orderIdForEdit
      const orderIdToSend = isEdit ? orderIdForEdit : (orderIdForEdit ?? (orderIdFromQuery ? parseInt(orderIdFromQuery, 10) : null))
      if (orderIdToSend != null) {
        payload.order_id = orderIdToSend
      }

      if (isEdit && id) {
        await apiClient.put(`/transactions/${id}`, payload)
        setSuccess('تراکنش با موفقیت بروزرسانی شد')
      } else {
        await apiClient.post('/transactions', payload)
        setSuccess('تراکنش به صورت پیش‌نویس ثبت شد. پس از بررسی و نشست پول به حساب، دکمه «تسویه» را بزنید.')
        
        setTimeout(() => {
          if (orderIdFromQuery) {
            navigate(`/orders/${orderIdFromQuery}`)
          } else if (customerId) {
            navigate(`/customers/${customerId}`)
          } else {
            navigate('/transactions')
          }
        }, 1500)
      }
    } 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 handleSubmitReceipt = async () => {
    if (!id) return
    setLoading(true)
    try {
      await apiClient.post(`/transactions/${id}/submit`)
      await loadTransaction(id)
      setSuccess('تراکنش با موفقیت ارسال شد')
    } catch (err: any) {
      setError(err.response?.data?.message || 'خطا در ارسال تراکنش')
    } finally {
      setLoading(false)
    }
  }

  const handleSettle = async () => {
    if (!id) return
    setLoading(true)
    try {
      await apiClient.post(`/transactions/${id}/settle`)
      await loadTransaction(id)
      setSuccess('تراکنش با موفقیت تسویه شد')
    } catch (err: any) {
      setError(err.response?.data?.message || 'خطا در تسویه تراکنش')
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!id) return
    if (!confirm('آیا از حذف این تراکنش اطمینان دارید؟')) return
    
    setLoading(true)
    try {
      await apiClient.delete(`/transactions/${id}`)
      setSuccess('تراکنش با موفقیت حذف شد')
      setTimeout(() => {
        if (customerId) {
          navigate(`/customers/${customerId}`)
        } else {
          navigate('/transactions')
        }
      }, 1000)
    } catch (err: any) {
      setError(err.response?.data?.message || 'خطا در حذف تراکنش')
      setLoading(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 ''
    try {
      return numberToWords(Math.floor(num)) + ' ' + getCurrencyLabel()
    } catch {
      return ''
    }
  }

  const isReadOnly = transaction?.status && transaction.status !== 'DRAFT'

  return (
    <>
      <PageMeta 
        title={isEdit ? 'ویرایش تراکنش | آیرون' : 'ثبت تراکنش جدید | آیرون'} 
        description={isEdit ? 'ویرایش تراکنش' : 'ثبت تراکنش جدید'} 
      />
      <PageBreadcrumb pageTitle={isEdit ? 'ویرایش تراکنش' : 'ثبت تراکنش جدید'} />

      <div className="mb-6">
        <button
          type="button"
          onClick={() => customerId ? navigate(`/customers/${customerId}`) : navigate('/transactions')}
          className="inline-flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-gray-600 transition hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
          aria-label={customerId ? 'بازگشت به صفحه مشتری' : 'بازگشت به لیست تراکنش‌ها'}
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 5l7 7-7 7" />
          </svg>
          {customerId ? 'بازگشت به صفحه مشتری' : 'بازگشت به لیست تراکنش‌ها'}
        </button>
      </div>

      {/* Alerts */}
      {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 - Only for new transactions: دو باکس جدا (بدهکار / بستانکار) */}
      {!isEdit && (
        <div className="mb-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
          {/* باکس مشتریان بدهکار */}
          <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div className="border-b border-gray-200 px-6 py-4 dark:border-gray-800">
              <div className="flex items-center gap-2">
                <svg className={`w-5 h-5 ${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-sm 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-6">
                <div className="h-6 w-6 animate-spin rounded-full border-4 border-error-500 border-t-transparent"></div>
              </div>
            ) : unbalancedCustomers.filter((i) => i.remaining.remaining_debt > 0.01).length === 0 ? (
              <div className="py-6 text-center text-sm text-gray-500 dark:text-gray-400">
                {BALANCE_LABELS.noDebt}
              </div>
            ) : (
              <div className="max-h-64 overflow-y-auto">
                <table className="w-full">
                  <thead className="sticky top-0 bg-gray-50 dark:bg-gray-800">
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">نام</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">موبایل</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">{BALANCE_LABELS.debtAmount}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500 dark:text-gray-400">عملیات</th>
                    </tr>
                  </thead>
                  <tbody 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 (
                          <tr
                            key={item.customer.id}
                            className={`hover:bg-gray-50 dark:hover:bg-white/[0.02] ${isSelectedFrom ? 'bg-brand-50 dark:bg-brand-500/10' : ''}`}
                          >
                            <td className="px-4 py-2 text-sm font-medium text-gray-800 dark:text-white/90">{item.customer.name}</td>
                            <td className="px-4 py-2 text-xs text-gray-500 dark:text-gray-400">{item.customer.mobile}</td>
                            <td className={`px-4 py-2 text-sm font-medium ${DEBT_CLASSES.text}`}>
                              {new Intl.NumberFormat('fa-IR').format(debtAmount)}
                            </td>
                            <td className="px-4 py-2">
                              <div className="flex items-center justify-center">
                                <button
                                  type="button"
                                  onClick={() => {
                                    setFromCustomerId(item.customer.id)
                                    setAmount(String(Math.floor(debtAmount)))
                                  }}
                                  className={`rounded px-2 py-1 text-xs font-medium transition ${
                                    isSelectedFrom
                                      ? DEBT_CLASSES.buttonActive
                                      : DEBT_CLASSES.button
                                  }`}
                                  title="انتخاب به عنوان پرداخت‌کننده"
                                >
                                  پرداخت‌کننده
                                </button>
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* باکس مشتریان بستانکار */}
          <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div className="border-b border-gray-200 px-6 py-4 dark:border-gray-800">
              <div className="flex items-center gap-2">
                <svg className={`w-5 h-5 ${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-sm 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-6">
                <div className="h-6 w-6 animate-spin rounded-full border-4 border-success-500 border-t-transparent"></div>
              </div>
            ) : unbalancedCustomers.filter((i) => i.remaining.remaining_credit > 0.01).length === 0 ? (
              <div className="py-6 text-center text-sm text-gray-500 dark:text-gray-400">
                {BALANCE_LABELS.noCredit}
              </div>
            ) : (
              <div className="max-h-64 overflow-y-auto">
                <table className="w-full">
                  <thead className="sticky top-0 bg-gray-50 dark:bg-gray-800">
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">نام</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">موبایل</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">{BALANCE_LABELS.creditAmount}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500 dark:text-gray-400">عملیات</th>
                    </tr>
                  </thead>
                  <tbody 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 (
                          <tr
                            key={item.customer.id}
                            className={`hover:bg-gray-50 dark:hover:bg-white/[0.02] ${isSelectedTo ? 'bg-brand-50 dark:bg-brand-500/10' : ''}`}
                          >
                            <td className="px-4 py-2 text-sm font-medium text-gray-800 dark:text-white/90">{item.customer.name}</td>
                            <td className="px-4 py-2 text-xs text-gray-500 dark:text-gray-400">{item.customer.mobile}</td>
                            <td className={`px-4 py-2 text-sm font-medium ${CREDIT_CLASSES.text}`}>
                              {new Intl.NumberFormat('fa-IR').format(creditAmount)}
                            </td>
                            <td className="px-4 py-2">
                              <div className="flex items-center justify-center">
                                <button
                                  type="button"
                                  onClick={() => {
                                    setToCustomerId(item.customer.id)
                                    setAmount(String(Math.floor(creditAmount)))
                                  }}
                                  className={`rounded px-2 py-1 text-xs font-medium transition ${
isSelectedTo
                                    ? CREDIT_CLASSES.buttonActive
                                    : CREDIT_CLASSES.button
                                  }`}
                                  title="انتخاب به عنوان دریافت‌کننده"
                                >
                                  دریافت‌کننده
                                </button>
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Form Card */}
      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div className="border-b border-gray-200 px-6 py-5 dark:border-gray-800">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="flex items-start gap-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand-100 dark:bg-brand-500/20">
                <svg className="h-5 w-5 text-brand-600 dark:text-brand-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-800 dark:text-white/90">
                  {isEdit ? 'اطلاعات تراکنش' : 'ثبت تراکنش جدید'}
                </h2>
                <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  پرداخت‌کننده، دریافت‌کننده، مبلغ و حساب مقصد را مشخص کنید.
                </p>
              </div>
            </div>
            {transaction && (
              <div className="flex items-center gap-3">
                {getStatusBadge(transaction.status)}
                {transaction.transaction_number && (
                  <span className="text-sm text-gray-500 dark:text-gray-400">
                    {transaction.transaction_number}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>

        {loadingData ? (
          <div className="flex items-center justify-center py-12">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="p-6">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              {/* From Customer (Payer) */}
              <div>
                <div className="mb-4">
                  <Label>پرداخت‌کننده *</Label>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">کسی که پول می‌دهد (به ما بدهکار است)</p>
                </div>
                <CustomerSelector
                  value={fromCustomerId}
                  onChange={(id, _name, bankAccounts) => {
                    setFromCustomerId(id)
                    setFromBankAccounts(bankAccounts || [])
                  }}
                  required
                  disabled={isReadOnly}
                />
                {fromBankAccounts.length > 0 && (
                  <div className="mt-3 p-3 rounded-lg bg-gray-50 dark:bg-gray-800">
                    <p className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">حساب‌های بانکی پرداخت‌کننده:</p>
                    <div className="space-y-2">
                      {fromBankAccounts.map((acc: any, idx: number) => (
                        <div key={idx} className="flex items-start justify-between gap-2 text-xs text-gray-700 dark:text-gray-300 space-y-1">
                          <div className="space-y-1 min-w-0">
                            <span className="font-medium">{acc.title || acc.bank_name || `حساب ${idx + 1}`}</span>
                            {acc.card_number && (
                              <span className="mr-2 font-mono" dir="ltr">
                                کارت: {(acc.card_number.match(/.{1,4}/g) ?? []).join('-')}
                              </span>
                            )}
                            {acc.account_number && (
                              <span className="mr-2 font-mono" dir="ltr">
                                شماره حساب: {acc.account_number}
                              </span>
                            )}
                            {acc.sheba && (
                              <span className="mr-2 font-mono" dir="ltr">
                                شبا: IR{acc.sheba}
                              </span>
                            )}
                          </div>
                          <button
                            type="button"
                            onClick={() => handleDeleteFromBankAccount(idx)}
                            className="shrink-0 rounded-lg p-1.5 text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-500/10"
                            title="حذف حساب"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* To Customer (Receiver) */}
              <div>
                <div className="mb-4">
                  <Label>دریافت‌کننده *</Label>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">کسی که پول می‌گیرد (از ما بستانکار است)</p>
                </div>
                <CustomerSelector
                  value={toCustomerId}
                  onChange={(id, _name, bankAccounts) => {
                    setToCustomerId(id)
                    setToBankAccounts(bankAccounts || [])
                    setSelectedToBankAccount(bankAccounts && bankAccounts.length > 0 ? 0 : null)
                  }}
                  required
                  disabled={isReadOnly}
                />
                {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('to')}
                        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-3 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">
                              <div className="flex items-center justify-between gap-2">
                                <div className="flex items-center gap-2">
                                  <span className="text-sm font-medium text-gray-800 dark:text-white/90">
                                    {acc.title || acc.bank_name || `حساب ${idx + 1}`}
                                  </span>
                                  {acc.bank_name && acc.title && (
                                    <span className="text-xs text-gray-500 dark:text-gray-400">({acc.bank_name})</span>
                                  )}
                                </div>
                                <button
                                  type="button"
                                  onClick={(e) => {
                                    e.preventDefault()
                                    e.stopPropagation()
                                    handleDeleteToBankAccount(idx)
                                  }}
                                  className="rounded-lg p-1.5 text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-500/10"
                                  title="حذف حساب"
                                >
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                  </svg>
                                </button>
                              </div>
                              <div className="mt-1 space-y-1">
                                {acc.card_number && (
                                  <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
                                    <span>کارت:</span>
                                    <span className="font-mono" dir="ltr">
                                      {(acc.card_number.match(/.{1,4}/g) ?? []).join('-')}
                                    </span>
                                    <button
                                      type="button"
                                      onClick={(e) => {
                                        e.preventDefault()
                                        navigator.clipboard.writeText(acc.card_number)
                                      }}
                                      className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                                      title="کپی"
                                    >
                                      <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                                      </svg>
                                    </button>
                                  </div>
                                )}
                                {acc.sheba && (
                                  <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
                                    <span>شبا:</span>
                                    <span className="font-mono" dir="ltr">IR{acc.sheba}</span>
                                    <button
                                      type="button"
                                      onClick={(e) => {
                                        e.preventDefault()
                                        navigator.clipboard.writeText(`IR${acc.sheba}`)
                                      }}
                                      className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                                      title="کپی"
                                    >
                                      <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                                      </svg>
                                    </button>
                                  </div>
                                )}
                                {acc.account_number && (
                                  <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
                                    <span>شماره حساب:</span>
                                    <span className="font-mono" dir="ltr">{acc.account_number}</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </label>
                        ))}
                      </div>
                    ) : (
                      <div className="p-4 rounded-lg border-2 border-dashed border-gray-200 dark:border-gray-700 text-center">
                        <svg className="mx-auto h-8 w-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                        </svg>
                        <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">حسابی ثبت نشده است</p>
                        <button
                          type="button"
                          onClick={() => openBankAccountModal('to')}
                          className="mt-2 text-xs font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400"
                        >
                          + افزودن حساب بانکی
                        </button>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Same Customer Warning */}
              {fromCustomerId && toCustomerId && fromCustomerId === toCustomerId && (
                <div className="md:col-span-2">
                  <div className="rounded-lg border border-error-200 bg-error-50 p-3 dark:border-error-500/20 dark:bg-error-500/10">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-error-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                      </svg>
                      <span className="text-sm font-medium text-error-600 dark:text-error-400">
                        پرداخت‌کننده و دریافت‌کننده نمی‌توانند یکی باشند
                      </span>
                    </div>
                  </div>
                </div>
              )}

              {/* Amount */}
              <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
                    disabled={isReadOnly}
                  />
                  {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>

              {/* Transaction Date */}
              <div>
                <Label>تاریخ و ساعت تراکنش *</Label>
                <DateTimePicker
                  value={transactionDate}
                  onChange={setTransactionDate}
                  placeholder="تاریخ و ساعت تراکنش را انتخاب کنید"
                  required
                  disabled={isReadOnly}
                  className={isReadOnly ? 'opacity-60' : ''}
                />
              </div>

              {/* Method */}
              <div>
                <Label>روش تراکنش *</Label>
                <select
                  className="mt-2 h-11 w-full appearance-none 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/10 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  value={method}
                  onChange={(e) => setMethod(e.target.value)}
                  required
                  disabled={isReadOnly}
                >
                  {methodOptions.map((opt) => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>

              {/* Reference */}
              <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="شماره پیگیری یا مرجع"
                  disabled={isReadOnly}
                />
              </div>

              {/* Notes */}
              <div className="md:col-span-2">
                <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={3}
                  placeholder="توضیحات اختیاری..."
                  disabled={isReadOnly}
                />
              </div>

              {/* سفارش مرتبط (اختیاری) - مثل انتخاب سفارش در تراکنش فلز */}
              <div className="md:col-span-2">
                <Label>سفارش مرتبط (اختیاری)</Label>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  سفارشات پرداخت‌کننده و دریافت‌کننده نمایش داده می‌شوند. با انتخاب یک سفارش، این تراکنش در صفحه همان سفارش نمایش داده می‌شود.
                </p>
                <div className="mt-2 flex items-center gap-3 flex-wrap">
                  <select
                    value={orderIdForEdit ?? ''}
                    onChange={(e) => setOrderIdForEdit(e.target.value ? parseInt(e.target.value, 10) : null)}
                    className="w-full max-w-md rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-brand-300 focus:outline-none focus:ring-2 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
                    disabled={(!fromCustomerId && !toCustomerId) || loadingOrdersForLink || isReadOnly}
                  >
                    <option value="">
                      {!fromCustomerId && !toCustomerId
                        ? 'ابتدا پرداخت‌کننده یا دریافت‌کننده را انتخاب کنید'
                        : loadingOrdersForLink
                          ? 'در حال بارگذاری...'
                          : 'بدون سفارش'}
                    </option>
                    {ordersForLink.map((o) => (
                      <option key={o.id} value={o.id}>
                        {o.label ?? `${o.order_number} (${o.order_type === 'BUY' ? 'خرید' : 'فروش'})`}
                      </option>
                    ))}
                  </select>
                  {orderIdForEdit && (
                    <Link
                      to={`/orders/${orderIdForEdit}`}
                      className="text-sm text-brand-500 hover:underline shrink-0"
                    >
                      مشاهده سفارش
                    </Link>
                  )}
                </div>
              </div>

              {/* Receipt Attachment - Only in edit mode */}
              {isEdit && (
                <div className="md:col-span-2">
                  <Label>تصویر فیش تراکنش</Label>
                  <div className="mt-2">
                    {attachmentError && (
                      <div className="mb-3 rounded-lg border border-error-200 bg-error-50 p-3 dark:border-error-500/20 dark:bg-error-500/10">
                        <p className="text-sm text-error-600 dark:text-error-400">{attachmentError}</p>
                      </div>
                    )}

                    {attachmentUrl && transaction?.attachment ? (
                      <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800">
                        <div className="flex items-start gap-4">
                          {/* Preview */}
                          {transaction.attachment.endsWith('.pdf') ? (
                            <div className="flex h-24 w-24 items-center justify-center rounded-lg bg-gray-200 dark:bg-gray-700">
                              <svg className="h-10 w-10 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                              </svg>
                            </div>
                          ) : (
                            <a 
                              href={attachmentUrl} 
                              target="_blank" 
                              rel="noopener noreferrer"
                              className="block"
                            >
                              <img
                                src={attachmentUrl}
                                alt="تصویر فیش"
                                className="h-24 w-24 rounded-lg object-cover border border-gray-300 dark:border-gray-600 hover:opacity-80 transition"
                                onError={(e) => {
                                  (e.target as HTMLImageElement).style.display = 'none'
                                }}
                              />
                            </a>
                          )}
                          
                          {/* Info & Actions */}
                          <div className="flex-1">
                            <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                              فیش تراکنش بارگذاری شده
                            </p>
                            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              برای مشاهده روی تصویر کلیک کنید
                            </p>
                            <div className="mt-3 flex items-center gap-2">
                              <a
                                href={attachmentUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="inline-flex items-center gap-1.5 rounded-lg bg-brand-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 transition"
                              >
                                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                </svg>
                                مشاهده
                              </a>
                              <button
                                type="button"
                                onClick={handleDeleteAttachment}
                                disabled={uploadingAttachment}
                                className="inline-flex items-center gap-1.5 rounded-lg bg-error-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-error-600 transition disabled:opacity-50"
                              >
                                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                                حذف
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="rounded-lg border-2 border-dashed border-gray-300 p-6 dark:border-gray-600">
                        <div className="flex flex-col items-center">
                          <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-700">
                            <svg className="h-6 w-6 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                            </svg>
                          </div>
                          <p className="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                            تصویر فیش تراکنش را بارگذاری کنید
                          </p>
                          <p className="mb-4 text-xs text-gray-500 dark:text-gray-400">
                            فرمت‌های مجاز: JPG, PNG, PDF (حداکثر ۲ مگابایت)
                          </p>
                          <label className="cursor-pointer">
                            <input
                              ref={fileInputRef}
                              type="file"
                              accept="image/jpeg,image/jpg,image/png,application/pdf"
                              onChange={handleAttachmentUpload}
                              className="hidden"
                              disabled={uploadingAttachment}
                            />
                            <span className="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600 transition disabled:opacity-50">
                              {uploadingAttachment ? (
                                <>
                                  <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="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                                  </svg>
                                  انتخاب فایل
                                </>
                              )}
                            </span>
                          </label>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {!isEdit && (
                <div className="md:col-span-2 rounded-lg bg-gray-50 dark:bg-gray-800 p-3">
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    تراکنش به صورت <strong>پیش‌نویس</strong> ذخیره می‌شود. پس از بررسی و اطمینان از نشست مبلغ به حساب، از صفحه ویرایش تراکنش دکمه «تسویه (به حساب نشست)» را بزنید.
                  </p>
                </div>
              )}
            </div>

            {/* Actions */}
            <div className="mt-8 flex flex-wrap items-center gap-3 border-t border-gray-200 pt-6 dark:border-gray-800">
              <button
                type="button"
                onClick={() => customerId ? navigate(`/customers/${customerId}`) : navigate('/transactions')}
                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>
              {!isReadOnly && (
                <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>
                      {isEdit ? 'در حال بروزرسانی...' : 'در حال ثبت...'}
                    </>
                  ) : (
                    <>
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                      {isEdit ? 'بروزرسانی تراکنش' : 'ثبت تراکنش'}
                    </>
                  )}
                </button>
              )}

              {/* Submit Button - Only for DRAFT transactions in edit mode */}
              {isEdit && transaction?.status === 'DRAFT' && (
                <button
                  type="button"
                  onClick={handleSubmitReceipt}
                  disabled={loading}
                  className="inline-flex items-center justify-center gap-2 rounded-xl bg-warning-500 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-warning-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                  </svg>
                  ارسال فیش
                </button>
              )}

              {/* Settle Button - Only for DRAFT or SUBMITTED transactions in edit mode */}
              {isEdit && (transaction?.status === 'DRAFT' || transaction?.status === 'SUBMITTED') && (
                <button
                  type="button"
                  onClick={handleSettle}
                  disabled={loading}
                  className="inline-flex items-center justify-center gap-2 rounded-xl bg-success-500 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-success-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  تسویه (به حساب نشست)
                </button>
              )}

              {/* Delete Button - Only for DRAFT transactions in edit mode */}
              {isEdit && transaction?.status === 'DRAFT' && (
                <button
                  type="button"
                  onClick={handleDelete}
                  disabled={loading}
                  className="inline-flex items-center justify-center gap-2 rounded-xl bg-error-500 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-error-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  حذف تراکنش
                </button>
              )}
            </div>
          </form>
        )}
      </div>

      {/* Bank Account Modal */}
      {showBankAccountModal && (
        <div className="fixed inset-0 z-50 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">
                حساب جدید برای {bankAccountModalFor === 'to' ? 'دریافت‌کننده' : 'پرداخت‌کننده'}
              </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>
      )}
    </>
  )
}
