import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate } from 'react-router-dom'
import Chart from 'react-apexcharts'
import { ApexOptions } from 'apexcharts'
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 { IfPermission } from '../../components/auth/RequirePermission'
import { BALANCE_LABELS, DEBT_CLASSES, CREDIT_CLASSES } from '../../constants/balance'

// Icons
const UsersIcon = () => (
  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
  </svg>
)

const OrdersIcon = () => (
  <svg className="w-6 h-6" 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 TransactionsIcon = () => (
  <svg className="w-6 h-6" 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 ClockIcon = () => (
  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
)

const PlusIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
  </svg>
)

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

const ArrowRightIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
  </svg>
)

// Donut Chart Component
interface DonutChartProps {
  series: number[]
  labels: string[]
  colors: string[]
  total?: number
  totalLabel?: string
}

const DonutChart = ({ series, labels, colors, total, totalLabel }: DonutChartProps) => {
  const options: ApexOptions = {
    chart: {
      fontFamily: 'Vazirmatn, Outfit, sans-serif',
      type: 'donut',
      height: 200,
    },
    colors: colors,
    labels: labels,
    legend: {
      show: false,
    },
    plotOptions: {
      pie: {
        donut: {
          size: '70%',
          labels: {
            show: true,
            name: {
              show: true,
              fontSize: '12px',
              fontWeight: 400,
              color: '#6B7280',
              offsetY: 20,
            },
            value: {
              show: true,
              fontSize: '24px',
              fontWeight: 700,
              color: '#1F2937',
              offsetY: -15,
              formatter: (val) => new Intl.NumberFormat('fa-IR').format(Number(val)),
            },
            total: {
              show: true,
              showAlways: true,
              label: totalLabel || 'مجموع',
              fontSize: '12px',
              fontWeight: 400,
              color: '#6B7280',
              formatter: () => total !== undefined 
                ? new Intl.NumberFormat('fa-IR').format(total)
                : new Intl.NumberFormat('fa-IR').format(series.reduce((a, b) => a + b, 0)),
            },
          },
        },
      },
    },
    dataLabels: {
      enabled: false,
    },
    stroke: {
      width: 0,
    },
    tooltip: {
      enabled: true,
      y: {
        formatter: (val) => new Intl.NumberFormat('fa-IR').format(val),
      },
    },
    responsive: [
      {
        breakpoint: 640,
        options: {
          chart: {
            height: 180,
          },
        },
      },
    ],
  }

  return (
    <Chart options={options} series={series} type="donut" height={200} />
  )
}

// Legend Item Component
interface LegendItemProps {
  color: string
  label: string
  value: number
  description?: string
  to?: string
}

const LegendItem = ({ color, label, value, description, to }: LegendItemProps) => {
  const content = (
    <div className={`flex items-center gap-3 py-2 ${to ? 'hover:bg-gray-50 dark:hover:bg-white/[0.02] -mx-2 px-2 rounded-lg cursor-pointer transition' : ''}`}>
      <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: color }}></div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between">
          <span className="text-sm text-gray-700 dark:text-gray-300">{label}</span>
          <span className="text-sm font-semibold text-gray-800 dark:text-white/90">
            {new Intl.NumberFormat('fa-IR').format(value)}
          </span>
        </div>
        {description && (
          <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">{description}</p>
        )}
      </div>
    </div>
  )
  
  return to ? <Link to={to}>{content}</Link> : content
}

interface PlanUsageData {
  plan: {
    id: number
    name: string
    slug: string
    max_users: number | null
    max_customers: number | null
    max_orders_per_month: number | null
    max_transactions_per_month: number | null
    max_metals_per_month: number | null
  } | null
  usage: {
    users_count: number
    customers_count: number
    orders_this_month_count: number
    transactions_this_month_count: number
    metals_this_month_count: number
  }
  limits: {
    users: number | null
    customers: number | null
    orders_this_month: number | null
    transactions_this_month: number | null
    metals_this_month: number | null
  }
}

interface DashboardStats {
  plan_usage?: PlanUsageData | null
  counts: {
    customers: number
    orders: number
    transactions: number
  }
  orders: {
    draft: number
    confirmed: number
    closed: number
  }
  transactions: {
    draft: number
    settled: number
    total_amount: number
  }
  balances: {
    debtors_count: number
    creditors_count: number
    total_debt: number
    total_credit: number
  }
  metal_balances: {
    debtors_count: number
    creditors_count: number
    total_debt: number
    total_credit: number
    by_product?: Array<{
      product_id: number
      product_name: string
      debt_grams: number
      credit_grams: number
      stock_grams?: number
    }>
  }
  recent: {
    orders: Array<{
      id: number
      order_number: string
      customer_name: string
      order_type: string
      status: string
      created_at: string
    }>
    transactions: Array<{
      id: number
      transaction_number: string
      from_customer: string
      to_customer: string
      amount: number
      status: string
      created_at: string
    }>
  }
  featured_customers?: Array<{
    id: number
    name: string
    mobile?: string
    money_debt: number
    money_credit: number
    metal_debt_grams: number
    metal_credit_grams: number
    metal_balances?: Array<{
      product_id: number
      product?: { id: number; name: string }
      debt_grams: number
      credit_grams: number
    }>
  }>
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('fa-IR').format(num)
}

const formatCurrencyNumber = (num: number) => {
  return new Intl.NumberFormat('fa-IR').format(Math.abs(num))
}

const formatWeight = (num: number) => {
  return 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: 'تسویه شده' },
    'PAID': { color: 'primary', label: 'پرداخت شده' },
    'CONFIRMED_TX': { 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>
}

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

// Balance Summary Card
const BalanceSummaryCard = ({
  title,
  debtorsCount,
  creditorsCount,
  totalDebt,
  totalCredit,
  formatValue,
  unit,
  debtLabel = BALANCE_LABELS.debtor,
  creditLabel = BALANCE_LABELS.creditor,
  debtorLink,
  creditorLink,
  icon,
  iconBg
}: {
  title: string
  debtorsCount: number
  creditorsCount: number
  totalDebt: number
  totalCredit: number
  formatValue: (num: number) => string
  unit?: string
  debtLabel?: string
  creditLabel?: string
  debtorLink?: string
  creditorLink?: string
  icon: React.ReactNode
  iconBg: string
}) => {
  return (
    <div className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6">
      {/* Header */}
      <div className="flex items-center gap-3 mb-5">
        <div className={`flex items-center justify-center w-10 h-10 rounded-xl ${iconBg}`}>
          {icon}
        </div>
        <div>
          <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">{title}</h4>
          <p className="text-xs text-gray-500 dark:text-gray-400">وضعیت تراز مشتریان</p>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-4">
        {debtorLink ? (
          <Link to={debtorLink} className={`rounded-xl ${DEBT_CLASSES.bg} p-3 ${DEBT_CLASSES.bgHover} transition cursor-pointer`}>
            <p className={`text-xs ${DEBT_CLASSES.text} mb-1`}>{debtLabel}</p>
            <p className={`text-lg font-bold ${DEBT_CLASSES.text}`}>{formatNumber(debtorsCount)} نفر</p>
            <p className={`text-xs ${DEBT_CLASSES.textMuted} mt-1`}>{formatValue(totalDebt)}</p>
          </Link>
        ) : (
          <div className={`rounded-xl ${DEBT_CLASSES.bg} p-3`}>
            <p className={`text-xs ${DEBT_CLASSES.text} mb-1`}>{debtLabel}</p>
            <p className={`text-lg font-bold ${DEBT_CLASSES.text}`}>{formatNumber(debtorsCount)} نفر</p>
            <p className={`text-xs ${DEBT_CLASSES.textMuted} mt-1`}>{formatValue(totalDebt)}</p>
          </div>
        )}
        {creditorLink ? (
          <Link to={creditorLink} className={`rounded-xl ${CREDIT_CLASSES.bg} p-3 ${CREDIT_CLASSES.bgHover} transition cursor-pointer`}>
            <p className={`text-xs ${CREDIT_CLASSES.text} mb-1`}>{creditLabel}</p>
            <p className={`text-lg font-bold ${CREDIT_CLASSES.text}`}>{formatNumber(creditorsCount)} نفر</p>
            <p className={`text-xs ${CREDIT_CLASSES.textMuted} mt-1`}>{formatValue(totalCredit)}</p>
          </Link>
        ) : (
          <div className={`rounded-xl ${CREDIT_CLASSES.bg} p-3`}>
            <p className={`text-xs ${CREDIT_CLASSES.text} mb-1`}>{creditLabel}</p>
            <p className={`text-lg font-bold ${CREDIT_CLASSES.text}`}>{formatNumber(creditorsCount)} نفر</p>
            <p className={`text-xs ${CREDIT_CLASSES.textMuted} mt-1`}>{formatValue(totalCredit)}</p>
          </div>
        )}
      </div>
    </div>
  )
}

export const DashboardPage = () => {
  const navigate = useNavigate()
  const { getCurrencyLabel } = useSettings()
  
  const formatCurrency = (num: number) => formatCurrencyNumber(num) + ' ' + getCurrencyLabel()
  
  const queryClient = useQueryClient()
  const [settlingTransactionId, setSettlingTransactionId] = useState<number | null>(null)

  const handleQuickSettleTransaction = async (e: React.MouseEvent, transactionId: number) => {
    e.preventDefault()
    e.stopPropagation()
    if (!confirm('آیا از تسویه این تراکنش (نشست به حساب) اطمینان دارید؟')) return
    setSettlingTransactionId(transactionId)
    try {
      await apiClient.post(`/transactions/${transactionId}/settle`)
      await queryClient.invalidateQueries({ queryKey: ['dashboard-stats'] })
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در تسویه تراکنش')
    } finally {
      setSettlingTransactionId(null)
    }
  }

  const { data: stats, isLoading } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: async () => {
      const res = await apiClient.get('/dashboard/stats')
      return (res.data?.data ?? res.data ?? res) as DashboardStats
    },
    refetchInterval: 30000,
  })

  // Calculate totals for charts
  const totalOrders = stats?.counts.orders ?? 0
  const totalTransactions = stats?.counts.transactions ?? 0

  // Calculate alerts
  const pendingOrders = stats?.orders.draft ?? 0
  const hasAlerts = pendingOrders > 0

  return (
    <>
      <PageMeta title="داشبورد | آیرون" description="پنل مدیریت آیرون" />
      <PageBreadcrumb pageTitle="داشبورد" />

      {isLoading ? (
        <div className="flex flex-col items-center justify-center py-16">
          <div className="h-10 w-10 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>
      ) : (
        <div className="space-y-8">
          {/* Page Header */}
          <div className="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">
                <ChartIcon />
              </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>
            <Link
              to="/reports"
              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="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>
              گزارشات
            </Link>
          </div>

          {/* Quick Action Cards */}
          <section>
            <div className="mb-4">
              <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="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {/* Orders Card */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03]">
                <div className="flex items-center justify-between mb-4">
                  <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">
                    <OrdersIcon />
                  </div>
                  <Link to="/orders" className="text-xs font-medium text-gray-500 hover:text-brand-600 dark:text-gray-400 dark:hover:text-brand-400 transition">
                    مشاهده همه
                  </Link>
                </div>
                <p className="text-2xl font-bold text-gray-800 dark:text-white/95">{formatNumber(stats?.counts.orders ?? 0)}</p>
                <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">سفارش ثبت‌شده</p>
                <IfPermission permission="create_orders">
                  <button
                    onClick={() => navigate('/orders/new')}
                    className="mt-4 w-full inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-brand-600"
                  >
                    <PlusIcon />
                    سفارش جدید
                  </button>
                </IfPermission>
              </div>

              {/* Money Transactions Card */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03]">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center justify-center w-11 h-11 rounded-xl bg-success-100 text-success-600 dark:bg-success-500/20 dark:text-success-400">
                    <TransactionsIcon />
                  </div>
                  <Link to="/transactions" className="text-xs font-medium text-gray-500 hover:text-success-600 dark:text-gray-400 dark:hover:text-success-400 transition">
                    مشاهده همه
                  </Link>
                </div>
                <p className="text-2xl font-bold text-gray-800 dark:text-white/95">{formatNumber(stats?.counts.transactions ?? 0)}</p>
                <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">تراکنش ریالی</p>
                <IfPermission permission="create_transactions">
                  <button
                    onClick={() => navigate('/transactions/new')}
                    className="mt-4 w-full inline-flex items-center justify-center gap-2 rounded-xl bg-success-500 px-4 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-success-600"
                  >
                    <PlusIcon />
                    تراکنش جدید
                  </button>
                </IfPermission>
              </div>

              {/* Customers Card */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition hover:shadow-md dark:border-gray-800 dark:bg-white/[0.03]">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center justify-center w-11 h-11 rounded-xl bg-indigo-100 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400">
                    <UsersIcon />
                  </div>
                  <Link to="/customers" className="text-xs font-medium text-gray-500 hover:text-indigo-600 dark:text-gray-400 dark:hover:text-indigo-400 transition">
                    مشاهده همه
                  </Link>
                </div>
                <p className="text-2xl font-bold text-gray-800 dark:text-white/95">{formatNumber(stats?.counts.customers ?? 0)}</p>
                <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">مشتری فعال</p>
                <IfPermission permission="create_customers">
                  <button
                    onClick={() => navigate('/customers/new')}
                    className="mt-4 w-full inline-flex items-center justify-center gap-2 rounded-xl bg-indigo-500 px-4 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-indigo-600"
                  >
                    <PlusIcon />
                    مشتری جدید
                  </button>
                </IfPermission>
              </div>
            </div>
          </section>

          {/* Alert Banner */}
          {hasAlerts && (
            <div className="rounded-2xl border border-warning-200 bg-warning-50 p-4 dark:border-warning-500/30 dark:bg-warning-500/10">
              <div className="flex flex-wrap items-center 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-warning-100 dark:bg-warning-500/20">
                    <ClockIcon />
                  </div>
                  <div>
                    <h3 className="text-sm font-semibold text-warning-800 dark:text-warning-200">
                      {formatNumber(pendingOrders)} سفارش در انتظار تایید
                    </h3>
                    <p className="mt-0.5 text-sm text-warning-600 dark:text-warning-400">
                      این سفارشات هنوز تایید نشده‌اند و نیاز به بررسی دارند.
                    </p>
                  </div>
                </div>
                <Link
                  to="/orders?status=DRAFT"
                  className="inline-flex items-center gap-2 rounded-xl bg-warning-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-warning-600"
                >
                  مشاهده سفارشات
                  <ArrowRightIcon />
                </Link>
              </div>
            </div>
          )}

          {/* Balance Summary */}
          <section>
            <div className="flex flex-wrap items-center justify-between gap-4 mb-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>
              <Link to="/customers" className="inline-flex items-center gap-1 text-sm font-medium text-brand-500 hover:text-brand-600 transition">
                لیست مشتریان
                <ArrowRightIcon />
              </Link>
            </div>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2 md:gap-6">
              <BalanceSummaryCard
                title="مانده ریالی"
                debtorsCount={stats?.balances.debtors_count ?? 0}
                creditorsCount={stats?.balances.creditors_count ?? 0}
                totalDebt={stats?.balances.total_debt ?? 0}
                totalCredit={stats?.balances.total_credit ?? 0}
                formatValue={formatCurrency}
                unit="ریالی"
                debtLabel="بدهکار (مشتری به ما بدهکار)"
                creditLabel="بستانکار (مشتری از ما بستانکار)"
                debtorLink="/customers?balance=money_debtor"
                creditorLink="/customers?balance=money_creditor"
                icon={<WalletIcon />}
                iconBg="bg-blue-50 text-blue-500 dark:bg-blue-500/10"
              />
              {/* مانده فلزی بر اساس هر محصول (جدول، گرم) */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6">
                <div className="flex items-center gap-3 mb-5">
                  <div className="flex items-center justify-center w-10 h-10 rounded-xl bg-amber-50 text-amber-500 dark:bg-amber-500/10">
                    <MetalIcon className="w-5 h-5" />
                  </div>
                  <div>
                    <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">مانده فلزی</h4>
                    <p className="text-xs text-gray-500 dark:text-gray-400">به تفکیک محصول (گرم)</p>
                  </div>
                </div>
                {(stats?.metal_balances?.by_product?.length ?? 0) > 0 ? (
                  <div className="overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-700">
                    <table className="w-full min-w-[280px] text-sm">
                      <thead>
                        <tr className="border-b border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800/50">
                          <th className="px-4 py-3 text-right font-medium text-gray-500 dark:text-gray-400">محصول</th>
                          <th className="px-4 py-3 text-right font-medium text-gray-500 dark:text-gray-400" title="مشتری به ما بدهکار فلز (سیستم طلبکار)">بدهکار (گرم)</th>
                          <th className="px-4 py-3 text-right font-medium text-gray-500 dark:text-gray-400" title="مشتری از ما بستانکار فلز (سیستم بدهکار)">بستانکار (گرم)</th>
                          <th className="px-4 py-3 text-right font-medium text-gray-500 dark:text-gray-400">موجودی (گرم)</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                        {stats?.metal_balances?.by_product
                          ?.map((row: { product_id: number; product_name: string; debt_grams: number; credit_grams: number; stock_grams?: number }) => {
                            const stockGrams = Number(row.stock_grams ?? 0)
                            return (
                            <tr key={row.product_id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                              <td className="px-4 py-3 font-medium text-gray-800 dark:text-white/90">{row.product_name || '—'}</td>
                              <td className="px-4 py-3">
                                {row.debt_grams > 0.001 ? (
                                  <span className={DEBT_CLASSES.text}>{new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(row.debt_grams)}</span>
                                ) : (
                                  <span className="text-gray-400">—</span>
                                )}
                              </td>
                              <td className="px-4 py-3">
                                {row.credit_grams > 0.001 ? (
                                  <span className={CREDIT_CLASSES.text}>{new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(row.credit_grams)}</span>
                                ) : (
                                  <span className="text-gray-400">—</span>
                                )}
                              </td>
                              <td className="px-4 py-3">
                                {stockGrams >= 0 ? (
                                  <span className="text-gray-800 dark:text-white/90">{new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(stockGrams)}</span>
                                ) : (
                                  <span className="text-gray-400">—</span>
                                )}
                              </td>
                            </tr>
                          );
                          })}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 dark:text-gray-400">مانده فلزی غیرصفر وجود ندارد</p>
                )}
              </div>
            </div>
          </section>

          {/* Featured Customers - Table */}
          {stats?.featured_customers && stats.featured_customers.length > 0 && (
            <section>
              <div className="flex flex-wrap items-center justify-between gap-4 mb-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-100 dark:bg-amber-500/20">
                    <svg className="h-5 w-5 text-amber-600 dark:text-amber-400" fill="currentColor" viewBox="0 0 24 24" aria-hidden>
                      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                    </svg>
                  </div>
                  <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>
                <Link
                  to="/customers"
                  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"
                >
                  همه مشتریان
                  <ArrowRightIcon />
                </Link>
              </div>
              <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[640px]">
                    <thead>
                      <tr className="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-800/50">
                        <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">مشتری</th>
                        <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">بدهکاری ریالی (سیستم طلبکار)</th>
                        <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">بستانکاری ریالی (سیستم بدهکار)</th>
                        <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">بدهکاری فلزی (سیستم طلبکار)</th>
                        <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">بستانکاری فلزی (سیستم بدهکار)</th>
                        <th className="px-5 py-4 w-24"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                      {stats.featured_customers.map((c) => (
                        <tr key={c.id} className="transition hover:bg-gray-50 dark:hover:bg-white/[0.03]">
                          <td className="px-5 py-4">
                            <Link to={`/customers/${c.id}`} className="flex items-center gap-3 group">
                              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-100 text-sm font-bold text-amber-700 dark:bg-amber-500/20 dark:text-amber-400">
                                {(c.name || 'م').charAt(0)}
                              </div>
                              <div>
                                <span className="font-medium text-gray-800 group-hover:text-brand-500 dark:text-white/90">{c.name}</span>
                                {c.mobile && (
                                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5" dir="ltr">{c.mobile}</p>
                                )}
                              </div>
                            </Link>
                          </td>
                          <td className="px-5 py-4 text-sm">
                            {(c.money_debt ?? 0) > 0.01 ? (
                              <span className={`font-medium ${DEBT_CLASSES.text}`}>{formatCurrency(c.money_debt)}</span>
                            ) : (
                              <span className="text-gray-400">—</span>
                            )}
                          </td>
                          <td className="px-5 py-4 text-sm">
                            {(c.money_credit ?? 0) > 0.01 ? (
                              <span className={`font-medium ${CREDIT_CLASSES.text}`}>{formatCurrency(c.money_credit)}</span>
                            ) : (
                              <span className="text-gray-400">—</span>
                            )}
                          </td>
                          <td className="px-5 py-4 text-sm">
                            {c.metal_balances && Array.isArray(c.metal_balances) && c.metal_balances.length > 0 ? (
                              <div className="flex flex-col gap-1">
                                {c.metal_balances.map((balance) => (
                                  balance.debt_grams > 0.001 && (
                                    <div key={balance.product_id} className="flex flex-col gap-0.5">
                                      <span className="text-xs text-gray-500 dark:text-gray-400">
                                        {balance.product?.name || `محصول ${balance.product_id}`}
                                      </span>
                                      <span className={`text-xs font-medium ${DEBT_CLASSES.text}`}>
                                        {formatWeight(balance.debt_grams)}
                                      </span>
                                    </div>
                                  )
                                ))}
                                {c.metal_balances.every((b) => b.debt_grams <= 0.001) && (
                                  <span className="text-gray-400">—</span>
                                )}
                              </div>
                            ) : (c.metal_debt_grams ?? 0) > 0.001 ? (
                              <span className={`font-medium ${DEBT_CLASSES.text}`}>{formatWeight(c.metal_debt_grams)}</span>
                            ) : (
                              <span className="text-gray-400">—</span>
                            )}
                          </td>
                          <td className="px-5 py-4 text-sm">
                            {c.metal_balances && Array.isArray(c.metal_balances) && c.metal_balances.length > 0 ? (
                              <div className="flex flex-col gap-1">
                                {c.metal_balances.map((balance) => (
                                  balance.credit_grams > 0.001 && (
                                    <div key={balance.product_id} className="flex flex-col gap-0.5">
                                      <span className="text-xs text-gray-500 dark:text-gray-400">
                                        {balance.product?.name || `محصول ${balance.product_id}`}
                                      </span>
                                      <span className={`text-xs font-medium ${CREDIT_CLASSES.text}`}>
                                        {formatWeight(balance.credit_grams)}
                                      </span>
                                    </div>
                                  )
                                ))}
                                {c.metal_balances.every((b) => b.credit_grams <= 0.001) && (
                                  <span className="text-gray-400">—</span>
                                )}
                              </div>
                            ) : (c.metal_credit_grams ?? 0) > 0.001 ? (
                              <span className={`font-medium ${CREDIT_CLASSES.text}`}>{formatWeight(c.metal_credit_grams)}</span>
                            ) : (
                              <span className="text-gray-400">—</span>
                            )}
                          </td>
                          <td className="px-5 py-4">
                            <Link
                              to={`/customers/${c.id}`}
                              className="inline-flex items-center gap-1 text-sm font-medium text-brand-500 hover:text-brand-600 dark:text-brand-400"
                            >
                              مشاهده
                              <ArrowRightIcon />
                            </Link>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </section>
          )}

          {/* Order and Transaction Status */}
          <section>
            <div className="mb-4">
              <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="grid grid-cols-1 gap-4 md:grid-cols-2 md:gap-6">
              {/* Order Status */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6">
                <div className="flex items-center justify-between mb-4">
                  <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">وضعیت سفارشات</h4>
                  <Link to="/orders" className="text-xs font-medium text-brand-500 hover:text-brand-600 transition">مشاهده همه</Link>
                </div>
                
                <div className="flex items-center gap-4">
                  {/* Donut Chart */}
                  <div className="w-1/2">
                    {totalOrders > 0 ? (
                      <DonutChart
                        series={[
                          stats?.orders.draft ?? 0,
                          stats?.orders.confirmed ?? 0,
                          stats?.orders.closed ?? 0,
                        ]}
                        labels={['پیش‌نویس', 'در حال پردازش', 'تکمیل شده']}
                        colors={['#9CA3AF', '#465FFF', '#22C55E']}
                        total={totalOrders}
                        totalLabel="کل سفارشات"
                      />
                    ) : (
                      <div className="h-[200px] flex items-center justify-center text-sm text-gray-400">
                        سفارشی ثبت نشده
                      </div>
                    )}
                  </div>
                  
                  {/* Legend */}
                  <div className="w-1/2 space-y-1">
                    <LegendItem
                      color="#9CA3AF"
                      label="پیش‌نویس"
                      value={stats?.orders.draft ?? 0}
                      description="نیاز به تایید"
                      to="/orders?status=DRAFT"
                    />
                    <LegendItem
                      color="#465FFF"
                      label="تایید شده"
                      value={stats?.orders.confirmed ?? 0}
                      description="در حال پردازش"
                      to="/orders?status=IN_PROGRESS"
                    />
                    <LegendItem
                      color="#22C55E"
                      label="تکمیل شده"
                      value={stats?.orders.closed ?? 0}
                      description="تکمیل شده"
                      to="/orders?status=COMPLETED"
                    />
                  </div>
                </div>
              </div>

              {/* Transaction Status */}
              <div className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6">
                <div className="flex items-center justify-between mb-4">
                  <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">وضعیت تراکنش‌های ریالی</h4>
                  <Link to="/transactions" className="text-xs font-medium text-brand-500 hover:text-brand-600 transition">مشاهده همه</Link>
                </div>
                
                <div className="flex items-center gap-4">
                  {/* Donut Chart */}
                  <div className="w-1/2">
                    {totalTransactions > 0 ? (
                      <DonutChart
                        series={[
                          stats?.transactions.draft ?? 0,
                          stats?.transactions.settled ?? 0,
                        ]}
                        labels={['پیش‌نویس', 'تسویه شده']}
                        colors={['#9CA3AF', '#22C55E']}
                        total={totalTransactions}
                        totalLabel="کل تراکنش‌ها"
                      />
                    ) : (
                      <div className="h-[200px] flex items-center justify-center text-sm text-gray-400">
                        تراکنشی ثبت نشده
                      </div>
                    )}
                  </div>
                  
                  {/* Legend */}
                  <div className="w-1/2 space-y-1">
                    <LegendItem
                      color="#9CA3AF"
                      label="پیش‌نویس"
                      value={stats?.transactions.draft ?? 0}
                      description="هنوز تسویه نشده"
                      to="/transactions?status=DRAFT"
                    />
                    <LegendItem
                      color="#22C55E"
                      label="تسویه شده"
                      value={stats?.transactions.settled ?? 0}
                      description="تایید شده"
                      to="/transactions?status=CONFIRMED"
                    />
                    <div className="pt-3 mt-3 border-t border-gray-200 dark:border-gray-700">
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-gray-500 dark:text-gray-400">مجموع تسویه</span>
                        <span className="text-sm font-bold text-success-600 dark:text-success-400">
                          {formatCurrency(stats?.transactions.total_amount ?? 0)}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

          {/* Recent Activity */}
          <section>
            <div className="mb-4">
              <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="grid grid-cols-1 gap-4 lg:grid-cols-2 lg:gap-6">
              {/* Recent Orders */}
              <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-5 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">
                      <OrdersIcon />
                    </div>
                    <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">آخرین سفارشات</h4>
                  </div>
                  <Link to="/orders" className="text-xs font-medium text-brand-500 hover:text-brand-600 transition">مشاهده همه</Link>
                </div>
                <div className="divide-y divide-gray-100 dark:divide-gray-800">
                  {stats?.recent.orders && stats.recent.orders.length > 0 ? (
                    stats.recent.orders.map((order) => (
                      <Link
                        key={order.id}
                        to={`/orders/${order.id}`}
                        className="flex items-center justify-between px-5 py-3 hover:bg-gray-50 dark:hover:bg-white/[0.02] transition"
                      >
                        <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 mt-0.5">{order.customer_name || 'بدون مشتری'}</p>
                        </div>
                        <div className="flex items-center gap-2">
                          {getOrderTypeBadge(order.order_type)}
                          {getStatusBadge(order.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-gray-100 dark:bg-gray-800">
                        <OrdersIcon />
                      </div>
                      <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">هنوز سفارشی ثبت نشده است</p>
                      <IfPermission permission="create_orders">
                        <button
                          onClick={() => navigate('/orders/new')}
                          className="mt-3 inline-flex items-center gap-2 rounded-xl bg-brand-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-600"
                        >
                          <PlusIcon />
                          ثبت اولین سفارش
                        </button>
                      </IfPermission>
                    </div>
                  )}
                </div>
              </div>

              {/* Recent Transactions */}
              <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-5 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-success-100 text-success-600 dark:bg-success-500/20 dark:text-success-400">
                      <TransactionsIcon />
                    </div>
                    <h4 className="text-sm font-semibold text-gray-800 dark:text-white/90">تراکنش‌های ریالی</h4>
                  </div>
                  <Link to="/transactions" className="text-xs font-medium text-brand-500 hover:text-brand-600 transition">مشاهده همه</Link>
                </div>
                <div className="divide-y divide-gray-100 dark:divide-gray-800">
                  {stats?.recent.transactions && stats.recent.transactions.length > 0 ? (
                    stats.recent.transactions.map((t) => (
                      <div
                        key={t.id}
                        className="flex items-center justify-between px-5 py-3 hover:bg-gray-50 dark:hover:bg-white/[0.02] transition"
                      >
                        <Link
                          to={`/transactions/${t.id}/edit`}
                          className="flex-1 min-w-0 flex items-center justify-between gap-3"
                        >
                          <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 mt-0.5">
                              {t.from_customer || '-'} ← {t.to_customer || '-'}
                            </p>
                          </div>
                          <div className="flex items-center gap-3">
                            <span className="text-sm font-medium text-gray-800 dark:text-white/90">
                              {formatCurrency(t.amount)}
                            </span>
                            {getStatusBadge(t.status)}
                          </div>
                        </Link>
                        {(t.status === 'DRAFT' || t.status === 'SUBMITTED' || t.status === 'IN_PROGRESS') && (
                          <button
                            type="button"
                            onClick={(e) => handleQuickSettleTransaction(e, t.id)}
                            disabled={settlingTransactionId === t.id}
                            className="shrink-0 rounded-lg p-1.5 text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-500/10 disabled:opacity-50"
                            title="تسویه (تایید نهایی)"
                          >
                            {settlingTransactionId === t.id ? (
                              <svg className="w-5 h-5 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 12h4z" />
                              </svg>
                            ) : (
                              <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>
                        )}
                      </div>
                    ))
                  ) : (
                    <div className="py-10 text-center">
                      <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-gray-100 dark:bg-gray-800">
                        <TransactionsIcon />
                      </div>
                      <p className="mt-3 text-sm text-gray-500 dark:text-gray-400">هنوز تراکنشی ثبت نشده است</p>
                      <IfPermission permission="create_transactions">
                        <button
                          onClick={() => navigate('/transactions/new')}
                          className="mt-3 inline-flex items-center gap-2 rounded-xl bg-success-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-success-600"
                        >
                          <PlusIcon />
                          ثبت اولین تراکنش
                        </button>
                      </IfPermission>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </section>
        </div>
      )}
    </>
  )
}
