import { useState, useEffect } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { apiClient } from '../../api/client'
import { useSettings } from '../../context/SettingsContext'
import PageMeta from '../../components/common/PageMeta'
import PageBreadcrumb from '../../components/common/PageBreadCrumb'
import Badge from '../../components/ui/badge/Badge'
import { DateRangeFilter } from '../../components/DateRangeFilter'
import { DEBT_CLASSES, CREDIT_CLASSES } from '../../constants/balance'

// Types
interface CustomerBalance {
  customer: {
    id: number
    name: string
    phone?: string
  }
  remaining: {
    remaining_debt: number
    remaining_credit: number
  }
}

interface CustomerMetalBalance {
  customer: {
    id: number
    name: string
    phone?: string
  }
  balances: Array<{
    product_id: number
    product?: { id: number; name: string }
    debt_grams: number
    credit_grams: number
  }>
  remaining: {
    remaining_debt: number
    remaining_credit: number
  }
}

interface UnbalancedOrder {
  id: number
  order_number: string
  customer?: { id: number; name: string; mobile?: string }
  customer_id: number
  order_type: string
  status: string
  money_status: string
  created_at: string
}

interface OpenOrder {
  id: number
  order_number: string
  customer?: { id: number; name: string; mobile?: string }
  customer_id: number
  order_type: string
  status: string
  created_at: string
}

interface UnallocatedTransaction {
  id: number
  transaction_number: string
  from_customer?: { id: number; name: string; mobile?: string }
  to_customer?: { id: number; name: string; mobile?: string }
  amount: number
  allocated_amount: number
  remaining_amount: number
  status: string
  created_at: string
}

// Utility functions
const formatNumber = (num: number) => new Intl.NumberFormat('fa-IR').format(num)
const formatWeight = (num: number) => new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(Math.abs(num)) + ' گرم'

const getStatusBadge = (status: string) => {
  const statusMap: Record<string, { color: 'primary' | 'success' | 'error' | 'warning' | 'light', label: string }> = {
    'DRAFT': { color: 'light', label: 'پیش‌نویس' },
    'IN_PROGRESS': { color: 'primary', label: 'در حال پردازش' },
    'COMPLETED': { color: 'success', label: 'تکمیل شده' },
    'CONFIRMED': { color: 'primary', label: 'تایید شده' },
    'CLOSED': { color: 'success', label: 'بسته شده' },
    'SETTLED': { color: 'success', label: 'تسویه شده' },
    'CONFIRMED_TX': { color: 'success', label: 'تایید شده' },
    'BALANCED': { color: 'success', label: 'متعادل' },
    'UNBALANCED': { color: 'warning', label: 'نامتعادل' },
    }
  const config = statusMap[status] || { color: 'light' as const, label: status }
  return <Badge color={config.color} variant="light" size="sm">{config.label}</Badge>
}

const getOrderTypeBadge = (type: string) => {
  if (type === 'BUY') return <Badge color="success" variant="light" size="sm">خرید نقره از مشتری</Badge>
  if (type === 'SELL') return <Badge color="error" variant="light" size="sm">فروش نقره به مشتری</Badge>
  return <Badge color="light" variant="light" size="sm">{type}</Badge>
}

// Tab types
type TabType = 'overview' | 'balances' | 'metal-balances' | 'orders' | 'transactions'

// Icons
const OverviewIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
  </svg>
)

const BalanceIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
)

const MetalIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
  </svg>
)

const OrderIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
  </svg>
)

const TransactionIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
  </svg>
)

const WarningIcon = () => (
  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
)

const RefreshIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
  </svg>
)

export const ReportsPage = () => {
  const { getCurrencyLabel } = useSettings()
  const [searchParams, setSearchParams] = useSearchParams()
  const initialTab = (searchParams.get('tab') as TabType) || 'overview'
  const initialFilter = searchParams.get('filter') || ''
  
  const formatCurrency = (num: number) => new Intl.NumberFormat('fa-IR').format(Math.abs(num)) + ' ' + getCurrencyLabel()
  
  const [activeTab, setActiveTab] = useState<TabType>(initialTab)
  const [balanceFilter, setBalanceFilter] = useState<'all' | 'debtors' | 'creditors'>(
    initialFilter === 'debtors' ? 'debtors' : initialFilter === 'creditors' ? 'creditors' : 'all'
  )
  const [fromDate, setFromDate] = useState(searchParams.get('from_date') || '')
  const [toDate, setToDate] = useState(searchParams.get('to_date') || '')

  // Queries
  const { data: customerBalances, isLoading: loadingBalances, refetch: refetchBalances } = useQuery({
    queryKey: ['customer-balances'],
    queryFn: async () => {
      const res = await apiClient.get('/reports/customer-balances?non_zero=true')
      return (res.data?.data ?? res.data ?? res) as CustomerBalance[]
    },
    enabled: activeTab === 'balances' || activeTab === 'overview',
  })

  const { data: metalBalances, isLoading: loadingMetalBalances, refetch: refetchMetalBalances } = useQuery({
    queryKey: ['customer-metal-balances'],
    queryFn: async () => {
      const res = await apiClient.get('/reports/customer-metal-balances?non_zero=true')
      return (res.data?.data ?? res.data ?? res) as CustomerMetalBalance[]
    },
    enabled: activeTab === 'metal-balances' || activeTab === 'overview',
  })

  const { data: unbalancedOrders, isLoading: loadingUnbalanced, refetch: refetchUnbalanced } = useQuery({
    queryKey: ['unbalanced-batches', fromDate, toDate],
    queryFn: async () => {
      const params = new URLSearchParams()
      if (fromDate) params.append('from_date', fromDate)
      if (toDate) params.append('to_date', toDate)
      const res = await apiClient.get(`/reports/unbalanced-batches?${params.toString()}`)
      return (res.data?.data ?? res.data ?? res) as UnbalancedOrder[]
    },
    enabled: activeTab === 'orders' || activeTab === 'overview',
  })

  const { data: openOrders, isLoading: loadingOpen, refetch: refetchOpen } = useQuery({
    queryKey: ['open-batches', fromDate, toDate],
    queryFn: async () => {
      const params = new URLSearchParams()
      if (fromDate) params.append('from_date', fromDate)
      if (toDate) params.append('to_date', toDate)
      const res = await apiClient.get(`/reports/open-batches?${params.toString()}`)
      return (res.data?.data ?? res.data ?? res) as OpenOrder[]
    },
    enabled: activeTab === 'orders' || activeTab === 'overview',
  })

  const { data: unallocatedTransactions, isLoading: loadingUnallocated, refetch: refetchUnallocated } = useQuery({
    queryKey: ['unallocated-transactions', fromDate, toDate],
    queryFn: async () => {
      const params = new URLSearchParams()
      if (fromDate) params.append('from_date', fromDate)
      if (toDate) params.append('to_date', toDate)
      const res = await apiClient.get(`/reports/unallocated-transactions?${params.toString()}`)
      return (res.data?.data ?? res.data ?? res) as UnallocatedTransaction[]
    },
    enabled: activeTab === 'transactions' || activeTab === 'overview',
  })

  // Update URL when tab changes
  useEffect(() => {
    const params = new URLSearchParams()
    if (activeTab !== 'overview') params.set('tab', activeTab)
    if (balanceFilter !== 'all' && activeTab === 'balances') params.set('filter', balanceFilter)
    if (fromDate) params.set('from_date', fromDate)
    if (toDate) params.set('to_date', toDate)
    setSearchParams(params, { replace: true })
  }, [activeTab, balanceFilter, fromDate, toDate, setSearchParams])

  // Filter balances
  const filteredBalances = customerBalances?.filter(b => {
    if (balanceFilter === 'debtors') return b.remaining.remaining_debt > 0.01
    if (balanceFilter === 'creditors') return b.remaining.remaining_credit > 0.01
    return true
  }) ?? []

  // Summary counts
  const debtorsCount = customerBalances?.filter(b => b.remaining.remaining_debt > 0.01).length ?? 0
  const creditorsCount = customerBalances?.filter(b => b.remaining.remaining_credit > 0.01).length ?? 0
  const totalDebt = customerBalances?.reduce((sum, b) => sum + b.remaining.remaining_debt, 0) ?? 0
  const totalCredit = customerBalances?.reduce((sum, b) => sum + b.remaining.remaining_credit, 0) ?? 0

  const refreshAll = () => {
    refetchBalances()
    refetchMetalBalances()
    refetchUnbalanced()
    refetchOpen()
    refetchUnallocated()
  }

  const tabs = [
    { id: 'overview' as TabType, label: 'نمای کلی', icon: <OverviewIcon /> },
    { id: 'balances' as TabType, label: 'مانده حساب', icon: <BalanceIcon /> },
    { id: 'metal-balances' as TabType, label: 'مانده فلز', icon: <MetalIcon /> },
    { id: 'orders' as TabType, label: 'سفارشات', icon: <OrderIcon /> },
    { id: 'transactions' as TabType, label: 'تراکنش‌ها', icon: <TransactionIcon /> },
  ]

  return (
    <>
      <PageMeta title="گزارشات | آیرون" description="گزارشات سیستم" />
      <PageBreadcrumb pageTitle="گزارشات" />

      {/* Page Header */}
      <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
        <div className="flex items-start gap-4">
          <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-brand-100 dark:bg-brand-500/20">
            <OverviewIcon />
          </div>
          <div>
            <h1 className="text-xl font-bold text-gray-800 dark:text-white/95">گزارشات</h1>
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
              مانده حساب، تراز فلز، سفارشات نامتعادل و تراکنش‌های تخصیص‌نیافته
            </p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <Link
            to="/"
            className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-4 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"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
            </svg>
            داشبورد
          </Link>
          <DateRangeFilter
            startDate={fromDate}
            endDate={toDate}
            onStartDateChange={setFromDate}
            onEndDateChange={setToDate}
          />
          {(fromDate || toDate) && (
            <button
              type="button"
              onClick={() => { setFromDate(''); setToDate('') }}
              className="h-10 rounded-xl border border-gray-200 bg-white px-3 text-sm font-medium text-gray-600 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700"
            >
              پاک کردن بازه
            </button>
          )}
          <button
            type="button"
            onClick={refreshAll}
            className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-4 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"
          >
            <RefreshIcon />
            بروزرسانی
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="mb-6">
        <nav className="flex flex-wrap gap-2" role="tablist">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              role="tab"
              aria-selected={activeTab === tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`inline-flex items-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-medium transition ${
                activeTab === tab.id
                  ? 'border-brand-500 bg-brand-50 text-brand-700 dark:border-brand-500 dark:bg-brand-500/20 dark:text-brand-300'
                  : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700'
              }`}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="space-y-6">
          {/* Summary Cards */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {/* Debtors */}
            <button
              type="button"
              onClick={() => { setActiveTab('balances'); setBalanceFilter('debtors') }}
              className="rounded-2xl border border-gray-200 bg-white p-5 text-right shadow-sm transition hover:border-error-200 hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03] dark:hover:border-error-500/40"
            >
              <div className={`flex items-center justify-center w-11 h-11 rounded-xl ${DEBT_CLASSES.iconBg}`}>
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6" />
                </svg>
              </div>
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">مشتریان بدهکار (به ما بدهکار)</p>
              <p className="mt-1 text-2xl font-bold text-gray-800 dark:text-white/95">{formatNumber(debtorsCount)} نفر</p>
              <p className={`mt-1 text-sm font-medium ${DEBT_CLASSES.text}`}>{formatCurrency(totalDebt)}</p>
            </button>

            {/* Creditors */}
            <button
              type="button"
              onClick={() => { setActiveTab('balances'); setBalanceFilter('creditors') }}
              className="rounded-2xl border border-gray-200 bg-white p-5 text-right shadow-sm transition hover:border-success-200 hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03] dark:hover:border-success-500/40"
            >
              <div className={`flex items-center justify-center w-11 h-11 rounded-xl ${CREDIT_CLASSES.iconBg}`}>
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
                </svg>
              </div>
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">مشتریان بستانکار (از ما بستانکار)</p>
              <p className="mt-1 text-2xl font-bold text-gray-800 dark:text-white/95">{formatNumber(creditorsCount)} نفر</p>
              <p className={`mt-1 text-sm font-medium ${CREDIT_CLASSES.text}`}>{formatCurrency(totalCredit)}</p>
            </button>

            {/* Unbalanced Orders */}
            <button
              type="button"
              onClick={() => setActiveTab('orders')}
              className="rounded-2xl border border-gray-200 bg-white p-5 text-right shadow-sm transition hover:border-warning-200 hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03] dark:hover:border-warning-500/40"
            >
              <div className="flex items-center justify-center w-11 h-11 rounded-xl bg-warning-100 text-warning-600 dark:bg-warning-500/20 dark:text-warning-400">
                <WarningIcon />
              </div>
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">سفارشات نامتعادل</p>
              <p className="mt-1 text-2xl font-bold text-gray-800 dark:text-white/95">
                {loadingUnbalanced ? '...' : formatNumber(unbalancedOrders?.length ?? 0)}
              </p>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">نیاز به بررسی</p>
            </button>

            {/* Unallocated Transactions */}
            <button
              type="button"
              onClick={() => setActiveTab('transactions')}
              className="rounded-2xl border border-gray-200 bg-white p-5 text-right shadow-sm transition hover:border-brand-200 hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03] dark:hover:border-brand-500/40"
            >
              <div className="flex items-center justify-center w-11 h-11 rounded-xl bg-brand-100 text-brand-600 dark:bg-brand-500/20 dark:text-brand-400">
                <TransactionIcon />
              </div>
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">تراکنش‌های تخصیص‌نیافته</p>
              <p className="mt-1 text-2xl font-bold text-gray-800 dark:text-white/95">
                {loadingUnallocated ? '...' : formatNumber(unallocatedTransactions?.length ?? 0)}
              </p>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">در انتظار تخصیص</p>
            </button>
          </div>

          {/* Quick Lists */}
          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
            {/* Recent Unbalanced */}
            <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
              <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-800">
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-warning-100 text-warning-600 dark:bg-warning-500/20 dark:text-warning-400">
                    <OrderIcon />
                  </div>
                  <h3 className="text-base font-semibold text-gray-800 dark:text-white/90">سفارشات نامتعادل</h3>
                </div>
                <button type="button" onClick={() => setActiveTab('orders')} className="text-sm font-medium text-brand-500 hover:text-brand-600 transition">
                  مشاهده همه
                </button>
              </div>
              <div className="divide-y divide-gray-200 dark:divide-gray-800">
                {loadingUnbalanced ? (
                  <div className="p-8 text-center">
                    <div className="h-8 w-8 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                    <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
                  </div>
                ) : unbalancedOrders && unbalancedOrders.length > 0 ? (
                  unbalancedOrders.slice(0, 5).map((order) => (
                    <Link
                      key={order.id}
                      to={`/orders/${order.id}`}
                      className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                    >
                      <div>
                        <p className="text-sm font-medium text-gray-800 dark:text-white/90">{order.order_number}</p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">{order.customer?.name || '-'}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        {getOrderTypeBadge(order.order_type)}
                        {getStatusBadge(order.money_status)}
                      </div>
                    </Link>
                  ))
                ) : (
                  <div className="py-10 text-center">
                    <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-success-100 dark:bg-success-500/10">
                      <svg className="w-6 h-6 text-success-500" 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>
                    </div>
                    <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">همه سفارشات متعادل هستند</p>
                  </div>
                )}
              </div>
            </div>

            {/* Recent Unallocated */}
            <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
              <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-800">
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-100 text-brand-600 dark:bg-brand-500/20 dark:text-brand-400">
                    <TransactionIcon />
                  </div>
                  <h3 className="text-base font-semibold text-gray-800 dark:text-white/90">تراکنش‌های تخصیص‌نیافته</h3>
                </div>
                <button type="button" onClick={() => setActiveTab('transactions')} className="text-sm font-medium text-brand-500 hover:text-brand-600 transition">
                  مشاهده همه
                </button>
              </div>
              <div className="divide-y divide-gray-200 dark:divide-gray-800">
                {loadingUnallocated ? (
                  <div className="p-8 text-center">
                    <div className="h-8 w-8 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                    <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
                  </div>
                ) : unallocatedTransactions && unallocatedTransactions.length > 0 ? (
                  unallocatedTransactions.slice(0, 5).map((t) => (
                    <Link
                      key={t.id}
                      to={`/transactions/${t.id}/edit`}
                      className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                    >
                      <div>
                        <p className="text-sm font-medium text-gray-800 dark:text-white/90">{t.transaction_number}</p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          {t.from_customer?.name || '-'} ← {t.to_customer?.name || '-'}
                        </p>
                      </div>
                      <div className="text-left">
                        <p className="text-sm font-medium text-warning-600 dark:text-warning-400">
                          {formatCurrency(t.remaining_amount)}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">باقیمانده</p>
                      </div>
                    </Link>
                  ))
                ) : (
                  <div className="py-10 text-center">
                    <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-success-100 dark:bg-success-500/10">
                      <svg className="w-6 h-6 text-success-500" 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>
                    </div>
                    <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">همه تراکنش‌ها تخصیص داده شده‌اند</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'balances' && (
        <div className="space-y-6">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h2 className="text-base font-semibold text-gray-800 dark:text-white/90">مانده حساب ریالی</h2>
              <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">تراز مشتریان با مانده غیرصفر</p>
            </div>
            <div className="flex rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
              {[
                { id: 'all' as const, label: 'همه' },
                { id: 'debtors' as const, label: 'بدهکاران (مشتری به ما بدهکار)' },
                { id: 'creditors' as const, label: 'بستانکاران (مشتری از ما بستانکار)' },
              ].map((f) => (
                <button
                  key={f.id}
                  type="button"
                  onClick={() => setBalanceFilter(f.id)}
                  className={`px-4 py-2.5 text-sm font-medium transition ${
                    balanceFilter === f.id
                      ? 'bg-brand-500 text-white'
                      : 'bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700'
                  }`}
                >
                  {f.label}
                </button>
              ))}
            </div>
          </div>

          {/* Summary */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            <div className="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
              <p className="text-sm text-gray-500 dark:text-gray-400">تعداد مشتری</p>
              <p className="mt-1 text-xl font-bold text-gray-800 dark:text-white/95">{formatNumber(filteredBalances.length)} نفر</p>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
              <p className="text-sm text-gray-500 dark:text-gray-400" title="مشتری به ما بدهکار (سیستم طلبکار)">مجموع بدهکاری</p>
              <p className={`mt-1 text-xl font-bold ${DEBT_CLASSES.text}`}>{formatCurrency(filteredBalances.reduce((s, b) => s + b.remaining.remaining_debt, 0))}</p>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
              <p className="text-sm text-gray-500 dark:text-gray-400" title="مشتری از ما بستانکار (سیستم بدهکار)">مجموع بستانکاری</p>
              <p className={`mt-1 text-xl font-bold ${CREDIT_CLASSES.text}`}>{formatCurrency(filteredBalances.reduce((s, b) => s + b.remaining.remaining_credit, 0))}</p>
            </div>
          </div>

          {/* Table */}
          <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
            {loadingBalances ? (
              <div className="p-12 text-center">
                <div className="h-10 w-10 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
              </div>
            ) : filteredBalances.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                    <tr>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">مشتری</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">بدهکاری (سیستم طلبکار)</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">بستانکاری (سیستم بدهکار)</th>
                      <th className="px-6 py-3"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                    {filteredBalances.map((item) => {
                      return (
                        <tr key={item.customer.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                          <td className="px-6 py-4">
                            <p className="text-sm font-medium text-gray-800 dark:text-white/90">{item.customer.name}</p>
                            {item.customer.phone && (
                              <p className="text-xs text-gray-500 dark:text-gray-400">{item.customer.phone}</p>
                            )}
                          </td>
                          <td className={`px-6 py-4 text-sm font-medium ${DEBT_CLASSES.text}`}>
                            {item.remaining.remaining_debt > 0.01 ? formatCurrency(item.remaining.remaining_debt) : '-'}
                          </td>
                          <td className={`px-6 py-4 text-sm font-medium ${CREDIT_CLASSES.text}`}>
                            {item.remaining.remaining_credit > 0.01 ? formatCurrency(item.remaining.remaining_credit) : '-'}
                          </td>
                          <td className="px-6 py-4">
                            <Link
                              to={`/customers/${item.customer.id}`}
                              className="text-sm text-brand-500 hover:text-brand-600"
                            >
                              مشاهده
                            </Link>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="py-12 text-center">
                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-gray-100 dark:bg-gray-800">
                  <BalanceIcon />
                </div>
                <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">موردی یافت نشد</p>
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === 'metal-balances' && (
        <div className="space-y-6">
          <div>
            <h2 className="text-base font-semibold text-gray-800 dark:text-white/90">مانده فلزی</h2>
            <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">تراز فلز مشتریان تفکیک شده بر اساس محصول</p>
          </div>
          <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
            {loadingMetalBalances ? (
              <div className="p-12 text-center">
                <div className="h-10 w-10 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
              </div>
            ) : metalBalances && metalBalances.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                    <tr>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">مشتری</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">محصول</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">بدهی (گرم)</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">بستانکاری (گرم)</th>
                      <th className="px-6 py-3"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                    {metalBalances.map((item) => {
                      const balances = Array.isArray(item.balances) ? item.balances : []
                      
                      if (balances.length === 0) {
                        return (
                          <tr key={item.customer.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                            <td className="px-6 py-4">
                              <p className="text-sm font-medium text-gray-800 dark:text-white/90">{item.customer.name}</p>
                            </td>
                            <td colSpan={3} className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">-</td>
                            <td className="px-6 py-4">
                              <Link
                                to={`/customers/${item.customer.id}`}
                                className="text-sm text-brand-500 hover:text-brand-600"
                              >
                                مشاهده
                              </Link>
                            </td>
                          </tr>
                        )
                      }
                      
                      return balances.map((balance, idx) => (
                        <tr key={`${item.customer.id}-${balance.product_id}`} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                          {idx === 0 && (
                            <td className="px-6 py-4" rowSpan={balances.length}>
                              <p className="text-sm font-medium text-gray-800 dark:text-white/90">{item.customer.name}</p>
                            </td>
                          )}
                          <td className="px-6 py-4 text-sm text-gray-700 dark:text-gray-300">
                            {balance.product?.name || `محصول ${balance.product_id}`}
                          </td>
                          <td className={`px-6 py-4 text-sm font-medium ${DEBT_CLASSES.text}`}>
                            {balance.debt_grams > 0.001 ? formatWeight(balance.debt_grams) : '-'}
                          </td>
                          <td className={`px-6 py-4 text-sm font-medium ${CREDIT_CLASSES.text}`}>
                            {balance.credit_grams > 0.001 ? formatWeight(balance.credit_grams) : '-'}
                          </td>
                          {idx === 0 && (
                            <td className="px-6 py-4" rowSpan={balances.length}>
                              <Link
                                to={`/customers/${item.customer.id}`}
                                className="text-sm text-brand-500 hover:text-brand-600"
                              >
                                مشاهده
                              </Link>
                            </td>
                          )}
                        </tr>
                      ))
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="py-12 text-center">
                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-gray-100 dark:bg-gray-800">
                  <MetalIcon />
                </div>
                <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">مشتری با مانده فلز غیرصفر یافت نشد</p>
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === 'orders' && (
        <div className="space-y-6">
          <div>
            <h2 className="text-base font-semibold text-gray-800 dark:text-white/90">سفارشات نامتعادل</h2>
            <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">
              {formatNumber(unbalancedOrders?.length ?? 0)} مورد نیاز به بررسی و تسویه
            </p>
          </div>
          <div>
            <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
              {loadingUnbalanced ? (
                <div className="p-12 text-center">
                  <div className="h-10 w-10 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                  <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
                </div>
              ) : unbalancedOrders && unbalancedOrders.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                      <tr>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">شماره سفارش</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">مشتری</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">نوع</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">وضعیت</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">وضعیت مالی</th>
                        <th className="px-6 py-3"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                      {unbalancedOrders.map((order) => (
                        <tr key={order.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                          <td className="px-6 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{order.order_number}</td>
                          <td className="px-6 py-4">
                            {order.customer ? (
                              <div>
                                <span className="text-sm text-gray-800 dark:text-white/90">{order.customer.name}</span>
                                {order.customer.mobile && (
                                  <p className="text-xs text-gray-500 dark:text-gray-400">{order.customer.mobile}</p>
                                )}
                              </div>
                            ) : (
                              <span className="text-sm text-gray-400">-</span>
                            )}
                          </td>
                          <td className="px-6 py-4">{getOrderTypeBadge(order.order_type)}</td>
                          <td className="px-6 py-4">{getStatusBadge(order.status)}</td>
                          <td className="px-6 py-4">{getStatusBadge(order.money_status)}</td>
                          <td className="px-6 py-4">
                            <Link to={`/orders/${order.id}`} className="text-sm text-brand-500 hover:text-brand-600">
                              مشاهده
                            </Link>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="py-12 text-center">
                  <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-success-100 dark:bg-success-500/10">
                    <svg className="w-6 h-6 text-success-500" 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>
                  </div>
                  <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">همه سفارشات متعادل هستند</p>
                </div>
              )}
            </div>
          </div>

          <div>
            <h2 className="mb-4 text-base font-semibold text-gray-800 dark:text-white/90">
              سفارشات باز
              <span className="mr-2 text-sm font-normal text-gray-500 dark:text-gray-400">
                ({formatNumber(openOrders?.length ?? 0)} مورد)
              </span>
            </h2>
            <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
              {loadingOpen ? (
                <div className="p-12 text-center">
                  <div className="h-10 w-10 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                  <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
                </div>
              ) : openOrders && openOrders.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                      <tr>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">شماره سفارش</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">مشتری</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">نوع</th>
                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">وضعیت</th>
                        <th className="px-6 py-3"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                      {openOrders.map((order) => (
                        <tr key={order.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                          <td className="px-6 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{order.order_number}</td>
                          <td className="px-6 py-4">
                            {order.customer ? (
                              <div>
                                <span className="text-sm text-gray-800 dark:text-white/90">{order.customer.name}</span>
                                {order.customer.mobile && (
                                  <p className="text-xs text-gray-500 dark:text-gray-400">{order.customer.mobile}</p>
                                )}
                              </div>
                            ) : (
                              <span className="text-sm text-gray-400">-</span>
                            )}
                          </td>
                          <td className="px-6 py-4">{getOrderTypeBadge(order.order_type)}</td>
                          <td className="px-6 py-4">{getStatusBadge(order.status)}</td>
                          <td className="px-6 py-4">
                            <Link to={`/orders/${order.id}`} className="text-sm text-brand-500 hover:text-brand-600">
                              مشاهده
                            </Link>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="py-12 text-center">
                  <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-gray-100 dark:bg-gray-800">
                    <OrderIcon />
                  </div>
                  <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">سفارش بازی وجود ندارد</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {activeTab === 'transactions' && (
        <div className="space-y-6">
          <div>
            <h2 className="text-base font-semibold text-gray-800 dark:text-white/90">تراکنش‌های تخصیص‌نیافته</h2>
            <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">
              {formatNumber(unallocatedTransactions?.length ?? 0)} مورد با مبلغ باقیمانده برای تخصیص به سفارش
            </p>
          </div>
          <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
            {loadingUnallocated ? (
              <div className="p-12 text-center">
                <div className="h-10 w-10 mx-auto animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
                <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
              </div>
            ) : unallocatedTransactions && unallocatedTransactions.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                    <tr>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">شماره تراکنش</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">از</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">به</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">مبلغ کل</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">تخصیص‌یافته</th>
                      <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400">باقیمانده</th>
                      <th className="px-6 py-3"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                    {unallocatedTransactions.map((t) => (
                      <tr key={t.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                        <td className="px-6 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{t.transaction_number}</td>
                        <td className="px-6 py-4">
                          {t.from_customer ? (
                            <div>
                              <span className="text-sm text-gray-800 dark:text-white/90">{t.from_customer.name}</span>
                              {t.from_customer.mobile && (
                                <p className="text-xs text-gray-500 dark:text-gray-400">{t.from_customer.mobile}</p>
                              )}
                            </div>
                          ) : (
                            <span className="text-sm text-gray-400">-</span>
                          )}
                        </td>
                        <td className="px-6 py-4">
                          {t.to_customer ? (
                            <div>
                              <span className="text-sm text-gray-800 dark:text-white/90">{t.to_customer.name}</span>
                              {t.to_customer.mobile && (
                                <p className="text-xs text-gray-500 dark:text-gray-400">{t.to_customer.mobile}</p>
                              )}
                            </div>
                          ) : (
                            <span className="text-sm text-gray-400">-</span>
                          )}
                        </td>
                        <td className="px-6 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{formatCurrency(t.amount)}</td>
                        <td className="px-6 py-4 text-sm text-success-600 dark:text-success-400">{formatCurrency(t.allocated_amount)}</td>
                        <td className="px-6 py-4 text-sm font-medium text-warning-600 dark:text-warning-400">{formatCurrency(t.remaining_amount)}</td>
                        <td className="px-6 py-4">
                          <Link to={`/transactions/${t.id}/edit`} className="text-sm text-brand-500 hover:text-brand-600">
                            مشاهده
                          </Link>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="py-12 text-center">
                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-success-100 dark:bg-success-500/10">
                  <svg className="w-6 h-6 text-success-500" 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>
                </div>
                <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">همه تراکنش‌ها تخصیص داده شده‌اند</p>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  )
}
