import { useEffect, useState, useCallback } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { apiClient } from '../../api/client'
import { useAuth } from '../../context/AuthContext'
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 { Pagination } from '../../components/Pagination'
import { SortableTh, type SortOrder } from '../../components/ui/table'
import { TableSkeleton } from '../../components/ui/skeleton'
import TableCheckbox from '../../components/form/input/TableCheckbox'
import { IfPermission } from '../../components/auth/RequirePermission'
import { QuickTransactionModal } from '../../components/QuickTransactionModal'
import { QuickMetalModal } from '../../components/QuickMetalModal'

interface Customer {
  id: number
  name: string
  code: string
  mobile?: string
}

interface OrderLine {
  product_id?: number
  grams: number
  purity?: number
  product?: { id: number; name: string; metal_type?: string; purity?: number }
}

interface Order {
  id: number
  order_number: string
  order_date: string
  order_type: string
  status: string
  money_status: string
  money_amount?: number
  customer?: Customer
  lines?: OrderLine[]
  remaining_money?: number
  remaining_metal?: Array<{ product_id: number; remaining_grams: number }>
  /** فلز تحویل/دریافت شده بالانسه (از API لیست) */
  metal_settled?: boolean
}

const getStatusBadge = (status: string, type: 'order' | 'metal' | 'money' | 'order_type') => {
  const statusMap: Record<string, { color: 'primary' | 'success' | 'error' | 'warning' | 'info' | 'light', label: string }> = {
    // Order status
    'DRAFT': { color: 'light', label: 'پیش‌نویس' },
    'IN_PROGRESS': { color: 'primary', label: 'در حال پردازش' },
    'COMPLETED': { color: 'success', label: 'تکمیل شده' },
    'CONFIRMED': { color: 'primary', label: 'تایید شده' },
    'CLOSED': { color: 'success', label: 'بسته شده' },
    // Metal/Money status
    'PENDING': { color: 'warning', label: 'در انتظار' },
    'PARTIAL': { color: 'info', label: 'جزئی' },
    'SETTLED': { color: 'success', label: 'تسویه' },
    // Order type
    'BUY': { color: 'success', label: 'خرید نقره از مشتری' },
    'SELL': { color: 'error', label: 'فروش نقره به مشتری' },
  }
  
  const config = statusMap[status] || { color: 'light' as const, label: status }
  return <Badge color={config.color} variant="light" size="sm">{config.label}</Badge>
}

export const OrdersPage = () => {
  const { isAdmin } = useAuth()
  const { formatCurrency, getCurrencyLabel } = useSettings()
  const [searchParams, setSearchParams] = useSearchParams()
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(true)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
  const [bulkDeleting, setBulkDeleting] = useState(false)
  const [bulkConfirming, setBulkConfirming] = useState(false)
  const [showTransactionModal, setShowTransactionModal] = useState(false)
  const [showMetalModal, setShowMetalModal] = useState(false)
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null)
  // Read filters from URL
  const [search, setSearch] = useState(searchParams.get('search') || '')
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '')
  const [typeFilter, setTypeFilter] = useState(searchParams.get('order_type') || '')
  const [moneyStatusFilter, setMoneyStatusFilter] = useState(searchParams.get('money_status') || '')
  const [fromDate, setFromDate] = useState(searchParams.get('from_date') || '')
  const [toDate, setToDate] = useState(searchParams.get('to_date') || '')
  const [page, setPage] = useState(Number(searchParams.get('page')) || 1)
  const [perPage, setPerPage] = useState(Number(searchParams.get('per_page')) || 20)
  const [sortBy, setSortBy] = useState<string | null>(searchParams.get('sort') || 'id')
  const [sortOrder, setSortOrder] = useState<SortOrder>((searchParams.get('order') as SortOrder) || 'desc')
  const [pagination, setPagination] = useState<{ current_page: number; last_page: number; per_page: number; total: number } | null>(null)

  const handleSort = (key: string) => {
    setSortBy(key)
    setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'))
    setPage(1)
    setSelectedIds(new Set())
  }

  const load = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      if (statusFilter) params.set('status', statusFilter)
      if (typeFilter) params.set('order_type', typeFilter)
      if (moneyStatusFilter) params.set('money_status', moneyStatusFilter)
      if (fromDate) params.set('from_date', fromDate)
      if (toDate) params.set('to_date', toDate)
      params.set('page', String(page))
      params.set('per_page', String(perPage))
      if (sortBy) params.set('sort', sortBy)
      params.set('order', sortOrder)
      
      const queryString = params.toString()
      const res = await apiClient.get(`/orders?${queryString}`)
      // API returns Laravel paginator { data, current_page, last_page, per_page, total }; apiClient returns response.data
      const paginatedData = res && typeof res === 'object' && 'current_page' in res ? res : (res?.data ?? res)

      if (paginatedData && typeof paginatedData === 'object' && 'data' in paginatedData) {
        setOrders((paginatedData as { data: Order[] }).data ?? [])
        setPagination({
          current_page: (paginatedData as { current_page: number }).current_page,
          last_page: (paginatedData as { last_page: number }).last_page,
          per_page: (paginatedData as { per_page: number }).per_page,
          total: (paginatedData as { total: number }).total,
        })
      } else {
        setOrders(Array.isArray(paginatedData) ? paginatedData : [])
        setPagination(null)
      }
    } finally {
      setLoading(false)
    }
  }, [statusFilter, typeFilter, moneyStatusFilter, fromDate, toDate, page, perPage, sortBy, sortOrder])

  // Update URL when filters change
  useEffect(() => {
    const params = new URLSearchParams()
    if (search) params.set('search', search)
    if (statusFilter) params.set('status', statusFilter)
    if (typeFilter) params.set('order_type', typeFilter)
    if (moneyStatusFilter) params.set('money_status', moneyStatusFilter)
    if (fromDate) params.set('from_date', fromDate)
    if (toDate) params.set('to_date', toDate)
    if (page > 1) params.set('page', String(page))
    if (perPage !== 20) params.set('per_page', String(perPage))
    if (sortBy && sortBy !== 'id') params.set('sort', sortBy)
    if (sortOrder !== 'desc') params.set('order', sortOrder)
    setSearchParams(params, { replace: true })
  }, [search, statusFilter, typeFilter, moneyStatusFilter, fromDate, toDate, page, perPage, sortBy, sortOrder, setSearchParams])

  useEffect(() => {
    void load()
  }, [load])
  
  // Filter orders locally only for search (API handles status/type filters)
  const filteredOrders = orders.filter((o) => {
    if (!search) return true
    const searchLower = search.toLowerCase()
    return (
      o.order_number?.toLowerCase().includes(searchLower) ||
      o.customer?.name?.toLowerCase().includes(searchLower) ||
      o.customer?.mobile?.toLowerCase().includes(searchLower)
    )
  })

  const handleDelete = async (orderId: number, orderNumber: string) => {
    if (!confirm(`آیا از حذف سفارش ${orderNumber} اطمینان دارید؟ این عملیات قابل بازگشت نیست.`)) {
      return
    }

    setDeletingId(orderId)
    try {
      await apiClient.delete(`/orders/${orderId}`)
      await load()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در حذف سفارش')
    } finally {
      setDeletingId(null)
    }
  }

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(new Set(filteredOrders.map((o) => o.id)))
    } else {
      setSelectedIds(new Set())
    }
  }

  const handleSelectOne = (id: number, checked: boolean) => {
    const newSelected = new Set(selectedIds)
    if (checked) {
      newSelected.add(id)
    } else {
      newSelected.delete(id)
    }
    setSelectedIds(newSelected)
  }

  const handleBulkConfirm = async () => {
    const draftIds = Array.from(selectedIds).filter((id) => 
      filteredOrders.find((o) => o.id === id)?.status === 'DRAFT'
    )
    if (draftIds.length === 0) {
      alert('فقط سفارش‌های پیش‌نویس قابل تایید هستند')
      return
    }

    if (!confirm(`آیا از تایید ${draftIds.length} سفارش انتخاب شده اطمینان دارید؟`)) {
      return
    }

    setBulkConfirming(true)
    try {
      await Promise.all(draftIds.map((id) => apiClient.post(`/orders/${id}/confirm`)))
      await load()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در تایید سفارش‌ها')
    } finally {
      setBulkConfirming(false)
    }
  }

  const handleBulkDelete = async () => {
    const ids = Array.from(selectedIds)
    if (ids.length === 0) return

    if (!confirm(`آیا از حذف ${ids.length} سفارش انتخاب شده اطمینان دارید؟ این عملیات قابل بازگشت نیست.`)) {
      return
    }

    setBulkDeleting(true)
    try {
      await Promise.all(ids.map((id) => apiClient.delete(`/orders/${id}`)))
      await load()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در حذف سفارش‌ها')
    } finally {
      setBulkDeleting(false)
    }
  }

  const allSelected = filteredOrders.length > 0 && filteredOrders.every((o) => selectedIds.has(o.id))
  const someSelected = selectedIds.size > 0
  
  // Filter selected orders by status for actions
  const selectedDraftIds = Array.from(selectedIds).filter((id) => 
    filteredOrders.find((o) => o.id === id)?.status === 'DRAFT'
  )
  return (
    <>
      <PageMeta title="سفارش‌ها | آیرون" description="لیست سفارش‌ها" />
      <PageBreadcrumb pageTitle="سفارش‌ها" />

      {/* Header */}
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-semibold text-gray-800 dark:text-white/90">
            لیست سفارش‌ها
            <span className="mr-2 font-normal text-gray-500 dark:text-gray-400">
              ({pagination?.total != null ? new Intl.NumberFormat('fa-IR').format(pagination.total) : loading ? '…' : '۰'}
              {' '}مورد)
            </span>
          </h2>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">مدیریت سفارش‌های سیستم</p>
        </div>
        <IfPermission permission="create_orders">
          <Link
            to="/orders/new"
            className="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-theme-xs hover:bg-brand-600"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            ایجاد سفارش جدید
          </Link>
        </IfPermission>
      </div>

      {/* Search and Filters */}
      <div className="mb-4 flex flex-wrap items-center gap-3">
        {/* Search */}
        <div className="relative flex-1 min-w-[200px]">
          <svg className="absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            placeholder="جستجو در شماره سفارش، مشتری..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-10 w-full rounded-lg border border-gray-200 bg-white pr-10 pl-4 text-sm text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
          />
        </div>
        
        {/* Status Filter */}
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        >
          <option value="">همه وضعیت‌ها</option>
          <option value="DRAFT">پیش‌نویس</option>
          <option value="IN_PROGRESS">در حال پردازش</option>
          <option value="COMPLETED">تکمیل شده</option>
          <option value="CONFIRMED">تایید شده</option>
          <option value="CLOSED">بسته شده</option>
        </select>
        
        {/* Type Filter */}
        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        >
          <option value="">همه انواع</option>
          <option value="BUY">خرید نقره از مشتری</option>
          <option value="SELL">فروش نقره به مشتری</option>
        </select>

        {/* Money Status Filter */}
        <select
          value={moneyStatusFilter}
          onChange={(e) => setMoneyStatusFilter(e.target.value)}
          className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        >
          <option value="">وضعیت مالی</option>
          <option value="UNSETTLED">تسویه نشده</option>
          <option value="PARTIAL">جزئی</option>
          <option value="SETTLED">تسویه شده</option>
        </select>

        {/* Date Range Filter */}
        <DateRangeFilter
          startDate={fromDate}
          endDate={toDate}
          onStartDateChange={setFromDate}
          onEndDateChange={setToDate}
        />

        {/* Clear Filters */}
        {(search || statusFilter || typeFilter || moneyStatusFilter || fromDate || toDate) && (
          <button
            type="button"
            onClick={() => {
              setSearch('')
              setStatusFilter('')
              setTypeFilter('')
              setMoneyStatusFilter('')
              setFromDate('')
              setToDate('')
            }}
            className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-600 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400 dark:hover:bg-gray-800"
          >
            پاک کردن فیلترها
          </button>
        )}
      </div>

      {/* Bulk Actions Bar */}
      {someSelected && (
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-purple-200 bg-purple-50 p-4 dark:border-purple-800 dark:bg-purple-900/20">
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium text-purple-700 dark:text-purple-300">
              {selectedIds.size.toLocaleString('fa-IR')} سفارش انتخاب شده
            </span>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <IfPermission permission="confirm_orders">
              {selectedDraftIds.length > 0 && (
                <button
                  onClick={handleBulkConfirm}
                  disabled={bulkConfirming || bulkDeleting}
                  className="rounded-lg bg-green-500 px-4 py-2 text-sm font-medium text-white hover:bg-green-600 disabled:opacity-50"
                >
                  {bulkConfirming ? 'در حال تایید...' : `تایید ${selectedDraftIds.length} مورد`}
                </button>
              )}
            </IfPermission>
            <IfPermission permission="delete_orders">
              {selectedIds.size > 0 && (
                <button
                  onClick={handleBulkDelete}
                  disabled={bulkConfirming || bulkDeleting}
                  className="rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white hover:bg-red-600 disabled:opacity-50"
                >
                  {bulkDeleting ? 'در حال حذف...' : `حذف ${selectedIds.size} مورد`}
                </button>
              )}
            </IfPermission>
            <button
              onClick={() => setSelectedIds(new Set())}
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300"
            >
              لغو انتخاب
            </button>
          </div>
        </div>
      )}

      {/* Main Card */}
      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">

        {/* Table */}
        {loading ? (
          <TableSkeleton rows={8} cols={9} showCheckbox />
        ) : filteredOrders.length === 0 ? (
          <div className="py-12 text-center">
            <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
            <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
              {search || statusFilter || typeFilter || moneyStatusFilter || fromDate || toDate ? 'سفارشی با این فیلترها یافت نشد.' : 'سفارشی ثبت نشده است.'}
            </p>
          </div>
        ) : (
          <>
            <div className="table-mobile-cards">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200 dark:border-gray-800">
                  <th className="w-12 px-5 py-4 text-right">
                    <TableCheckbox checked={allSelected} onChange={handleSelectAll} />
                  </th>
                  <SortableTh sortKey="order_number" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    شماره سفارش
                  </SortableTh>
                  <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">مشتری</th>
                  <SortableTh sortKey="order_date" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    تاریخ
                  </SortableTh>
                  <SortableTh sortKey="order_type" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    نوع
                  </SortableTh>
                  <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">وزن فلز</th>
                  <SortableTh sortKey="money_amount" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    مبلغ
                  </SortableTh>
                  <SortableTh sortKey="status" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    وضعیت
                  </SortableTh>
                  <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">عملیات</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                {filteredOrders.map((o) => (
                  <tr key={o.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <td className="px-5 py-4 table-mobile-checkbox" data-label="انتخاب">
                      <TableCheckbox
                        checked={selectedIds.has(o.id)}
                        onChange={(checked) => handleSelectOne(o.id, checked)}
                      />
                    </td>
                    <td className="px-5 py-4 table-mobile-primary" data-label="شماره سفارش">
                      <Link to={`/orders/${o.id}`} className="text-sm font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300">
                        {o.order_number}
                      </Link>
                    </td>
                    <td className="px-5 py-4" data-label="مشتری">
                      {o.customer ? (
                        <div>
                          <Link to={`/customers/${o.customer.id}`} className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90">
                            {o.customer.name}
                          </Link>
                          {o.customer.mobile && (
                            <p className="text-xs text-gray-500 dark:text-gray-400">
                              {o.customer.mobile}
                            </p>
                          )}
                        </div>
                      ) : (
                        <span className="text-sm text-gray-400">-</span>
                      )}
                    </td>
                    <td className="px-5 py-4 text-sm text-gray-500 dark:text-gray-400" data-label="تاریخ">
                      {o.order_date ? new Date(o.order_date).toLocaleString('fa-IR', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                      }) : '-'}
                    </td>
                    <td className="px-5 py-4" data-label="نوع">{getStatusBadge(o.order_type, 'order_type')}</td>
                    <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-400" data-label="وزن فلز">
                      <OrderMetalCell order={o} />
                    </td>
                    <td className="px-5 py-4 text-sm font-medium text-gray-800 dark:text-white/90" data-label="مبلغ">
                      <OrderMoneyCell order={o} />
                    </td>
                    <td className="px-5 py-4" data-label="وضعیت">{getStatusBadge(o.status, 'order')}</td>
                    <td className="px-5 py-4 table-mobile-actions">
                      <div className="flex flex-wrap items-center gap-1.5">
                        <Link
                          to={`/orders/${o.id}`}
                          className="rounded-lg p-1.5 text-brand-500 hover:bg-brand-50 dark:hover:bg-brand-500/10"
                          title="مشاهده"
                        >
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        </Link>
                        <IfPermission permission="update_orders">
                          {o.status === 'DRAFT' && (
                            <Link
                              to={`/orders/${o.id}/edit`}
                              className="rounded-lg p-1.5 text-success-500 hover:bg-success-50 dark:hover:bg-success-500/10"
                              title="ویرایش"
                            >
                              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                              </svg>
                            </Link>
                          )}
                        </IfPermission>
                        <IfPermission permission="create_transactions">
                          <button
                            onClick={() => {
                              setSelectedOrder(o)
                              setShowTransactionModal(true)
                            }}
                            disabled={o.money_status === 'SETTLED'}
                            title={o.money_status === 'SETTLED' ? 'تسویه شده' : 'افزودن تراکنش مالی'}
                            className="rounded-lg p-1.5 text-amber-600 hover:bg-amber-50 dark:text-amber-400 dark:hover:bg-amber-500/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent dark:disabled:hover:bg-transparent"
                          >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                          </button>
                        </IfPermission>
                        <IfPermission permission="create_metals">
                          <button
                            onClick={() => {
                              setSelectedOrder(o)
                              setShowMetalModal(true)
                            }}
                            disabled={o.metal_settled === true}
                            title={o.metal_settled === true ? 'تحویل/دریافت بالانسه' : 'فلز (تحویل/دریافت)'}
                            className="rounded-lg p-1.5 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-500/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent dark:disabled:hover:bg-transparent"
                          >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                            </svg>
                          </button>
                        </IfPermission>
                        <IfPermission permission="delete_orders">
                          <button
                            type="button"
                            onClick={() => handleDelete(o.id, o.order_number)}
                            disabled={deletingId === o.id}
                            className="rounded-lg p-1.5 text-error-500 hover:bg-error-50 dark:hover:bg-error-500/10 disabled:opacity-50"
                            title="حذف"
                          >
                          {deletingId === o.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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                            </svg>
                          ) : (
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          )}
                          </button>
                        </IfPermission>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {pagination && (
            <Pagination
              currentPage={pagination.current_page}
              lastPage={pagination.last_page}
              perPage={pagination.per_page}
              total={pagination.total}
              onPageChange={(newPage) => {
                setPage(newPage)
                setSelectedIds(new Set())
              }}
              onPerPageChange={(newPerPage) => {
                setPerPage(newPerPage)
                setPage(1)
                setSelectedIds(new Set())
              }}
            />
          )}
          </>
        )}
      </div>

      {/* Quick Transaction Modal */}
      {selectedOrder && (
        <>
          <QuickTransactionModal
            isOpen={showTransactionModal}
            onClose={() => {
              setShowTransactionModal(false)
              setSelectedOrder(null)
            }}
            orderId={selectedOrder.id}
            orderNumber={selectedOrder.order_number}
            customerId={selectedOrder.customer?.id}
            orderType={selectedOrder.order_type === 'BUY' || selectedOrder.order_type === 'SELL' ? selectedOrder.order_type : undefined}
            onSuccess={() => {
              load()
            }}
          />
          <QuickMetalModal
            isOpen={showMetalModal}
            onClose={() => {
              setShowMetalModal(false)
              setSelectedOrder(null)
            }}
            orderId={selectedOrder.id}
            orderNumber={selectedOrder.order_number}
            customerId={selectedOrder.customer?.id}
            onSuccess={() => {
              load()
            }}
          />
        </>
      )}
    </>
  )
}

// Component to display order metal by product with remaining balance
const OrderMetalCell = ({ order }: { order: Order }) => {
  const [metalRemainingByProduct, setMetalRemainingByProduct] = useState<Map<number, { remaining: number; total: number }>>(new Map())
  const [loading, setLoading] = useState(false)

  const loadRemaining = useCallback(async () => {
    if (!order.id) return
    setLoading(true)
    try {
      const res = await apiClient.get(`/orders/${order.id}/remaining-balances`)
      const responseData = res?.data || res
      const metalData = responseData?.metal || []
      const byProductMap = new Map<number, { remaining: number; total: number }>()
      metalData.forEach((item: { product_id?: number; remaining_grams?: number; line_grams?: number }) => {
        const productId = item.product_id
        if (productId) {
          byProductMap.set(productId, {
            remaining: item.remaining_grams || 0,
            total: item.line_grams || 0,
          })
        }
      })
      setMetalRemainingByProduct(byProductMap)
    } catch {
      setMetalRemainingByProduct(new Map())
    } finally {
      setLoading(false)
    }
  }, [order.id])

  useEffect(() => {
    loadRemaining()
  }, [loadRemaining])

  // گروه‌بندی خطوط به تفکیک محصول
  const byProduct = (order.lines || []).reduce<Map<number | string, { grams: number; name: string; productId?: number }>>((acc, line) => {
    const grams = Number(line.grams) || 0
    if (grams <= 0) return acc
    const productId = line.product_id ?? line.product?.id
    const key = productId ?? line.product?.name ?? 'other'
    const name = line.product?.name || `محصول ${productId ?? '—'}`
    const cur = acc.get(key)
    if (cur) {
      cur.grams += grams
    } else {
      acc.set(key, { grams, name, productId })
    }
    return acc
  }, new Map())

  if (byProduct.size === 0) {
    return <span>-</span>
  }

  return (
    <div className="space-y-1 min-w-[140px]">
      {Array.from(byProduct.entries()).map(([key, { name, grams, productId }]) => {
        const remainingData = productId ? metalRemainingByProduct.get(productId) : null
        const hasRemaining = remainingData && remainingData.remaining > 0.001
        const isBalanced = remainingData && remainingData.remaining <= 0.001 && remainingData.total > 0

        return (
          <div key={String(key)} className="flex flex-col gap-0.5">
            <span className="text-xs text-gray-500 dark:text-gray-400 truncate" title={name}>{name}</span>
            {loading ? (
              <span className="text-xs text-gray-400">...</span>
            ) : hasRemaining && remainingData ? (
              <span className="text-xs text-gray-800 dark:text-white/90 tabular-nums">
                <span className="text-blue-600 dark:text-blue-400">
                  {remainingData.remaining.toLocaleString('fa-IR', { maximumFractionDigits: 2 })}
                </span>
                {' '}گرم از{' '}
                <span className="text-gray-600 dark:text-gray-400">
                  {remainingData.total.toLocaleString('fa-IR', { maximumFractionDigits: 2 })}
                </span>
                {' '}گرم
              </span>
            ) : isBalanced && remainingData ? (
              <span className="text-xs text-success-600 dark:text-success-400 tabular-nums">
                {remainingData.total.toLocaleString('fa-IR', { maximumFractionDigits: 2 })} گرم
              </span>
            ) : (
              <span className="text-xs text-gray-800 dark:text-white/90 tabular-nums">
                {grams.toLocaleString('fa-IR', { maximumFractionDigits: 2 })} گرم
              </span>
            )}
          </div>
        )
      })}
    </div>
  )
}

// Component to display order money with remaining balance
const OrderMoneyCell = ({ order }: { order: Order }) => {
  const { formatCurrency, getCurrencyLabel } = useSettings()
  const [remainingMoney, setRemainingMoney] = useState<number | null>(null)
  const [inProgressMoney, setInProgressMoney] = useState<number>(0)
  const [loading, setLoading] = useState(false)

  const loadRemaining = useCallback(async () => {
    if (!order.id) return
    setLoading(true)
    try {
      const res = await apiClient.get(`/orders/${order.id}/remaining-balances`)
      const responseData = res?.data || res
      const money = responseData?.money || {}
      setRemainingMoney(money.remaining_amount ?? 0)
      setInProgressMoney(money.direct_in_progress_amount ?? 0)
    } catch (err) {
      console.error('Error loading money remaining balance:', err)
      setRemainingMoney(null)
      setInProgressMoney(0)
    } finally {
      setLoading(false)
    }
  }, [order.id])

  useEffect(() => {
    loadRemaining()
  }, [loadRemaining])

  if (!order.money_amount) {
    return <span>-</span>
  }

  return (
    <div className="space-y-1">
      <div>
        {formatCurrency(order.money_amount)} {getCurrencyLabel()}
      </div>
      {loading ? (
        <div className="text-xs text-gray-400">...</div>
      ) : (
        <>
          {remainingMoney !== null && remainingMoney > 0.01 && (
            <div className="text-xs text-amber-600 dark:text-amber-400">
              مانده: {formatCurrency(remainingMoney)} {getCurrencyLabel()}
            </div>
          )}
          {remainingMoney !== null && remainingMoney <= 0.01 && (
            <div className="text-xs text-success-600 dark:text-success-400">بالانس</div>
          )}
          {inProgressMoney > 0.01 && (
            <div className="text-xs text-blue-600 dark:text-blue-400" title="پیش‌نویس یا در انتظار تسویه">
              در حال پردازش: {formatCurrency(inProgressMoney)} {getCurrencyLabel()}
            </div>
          )}
        </>
      )}
    </div>
  )
}
