import { useEffect, useState, useCallback } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
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 { 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'

interface Transaction {
  id: number
  transaction_number: string
  amount: number
  transaction_date: string
  status: string
  method: string
  remaining_amount?: number
  from_customer?: { id: number; name: string; mobile?: string }
  to_customer?: { id: number; name: string; mobile?: string }
}

const getStatusBadge = (status: string) => {
  const statusMap: Record<string, { color: 'primary' | 'success' | 'error' | 'warning' | 'light', label: string }> = {
    'DRAFT': { color: 'light', label: 'پیش‌نویس' },
    'SUBMITTED': { color: 'warning', label: 'ارسال شده' },
    'CONFIRMED': { color: 'success', label: 'تایید شده' },
    'SETTLED': { color: 'success', label: 'تسویه شده' },
    'IN_PROGRESS': { color: 'primary', label: 'در حال پردازش' },
    'PAID': { color: 'primary', 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 TransactionsPage = () => {
  const { formatCurrency, getCurrencyLabel } = useSettings()
  const [searchParams, setSearchParams] = useSearchParams()
  const [transactions, setTransactions] = useState<Transaction[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
  const [bulkDeleting, setBulkDeleting] = useState(false)
  const [bulkVerifying, setBulkVerifying] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [settlingId, setSettlingId] = useState<number | null>(null)
  
  // Read filters from URL
  const [search, setSearch] = useState(searchParams.get('search') || '')
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '')
  const [methodFilter, setMethodFilter] = useState(searchParams.get('method') || '')
  const [unallocatedFilter, setUnallocatedFilter] = useState(searchParams.get('unallocated') === 'true')
  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 loadTransactions = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      if (statusFilter) params.append('status', statusFilter)
      if (methodFilter) params.append('method', methodFilter)
      if (unallocatedFilter) params.append('unallocated', 'true')
      if (fromDate) params.append('from_date', fromDate)
      if (toDate) params.append('to_date', toDate)
      params.append('page', String(page))
      params.append('per_page', String(perPage))
      if (sortBy) params.append('sort', sortBy)
      params.append('order', sortOrder)
      const res = await apiClient.get(`/transactions?${params.toString()}`)
      // 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) {
        setTransactions((paginatedData as { data: Transaction[] }).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 {
        setTransactions(Array.isArray(paginatedData) ? paginatedData : [])
        setPagination(null)
      }
    } finally {
      setLoading(false)
    }
  }, [statusFilter, methodFilter, unallocatedFilter, 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 (methodFilter) params.set('method', methodFilter)
    if (unallocatedFilter) params.set('unallocated', 'true')
    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, methodFilter, unallocatedFilter, fromDate, toDate, page, perPage, sortBy, sortOrder, setSearchParams])

  useEffect(() => {
    loadTransactions()
  }, [loadTransactions])
  
  // Filter transactions based on search
  const filteredTransactions = transactions.filter((t) => {
    if (!search) return true
    const searchLower = search.toLowerCase()
    return (
      t.transaction_number?.toLowerCase().includes(searchLower) ||
      t.from_customer?.name?.toLowerCase().includes(searchLower) ||
      t.from_customer?.mobile?.toLowerCase().includes(searchLower) ||
      t.to_customer?.name?.toLowerCase().includes(searchLower) ||
      t.to_customer?.mobile?.toLowerCase().includes(searchLower) ||
      String(t.amount).includes(search)
    )
  })

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      // Select all filtered transactions (any status)
      setSelectedIds(new Set(filteredTransactions.map((t) => t.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 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(`/transactions/${id}`)))
      await loadTransactions()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در حذف تراکنش‌ها')
    } finally {
      setBulkDeleting(false)
    }
  }

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

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

    setBulkVerifying(true)
    try {
      await Promise.all(draftIds.map((id) => apiClient.post(`/transactions/${id}/settle`)))
      await loadTransactions()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در تایید تراکنش‌ها')
    } finally {
      setBulkVerifying(false)
    }
  }

  const handleQuickSettle = async (id: number) => {
    const t = transactions.find((x) => x.id === id)
    if (!t || (t.status !== 'DRAFT' && t.status !== 'SUBMITTED' && t.status !== 'IN_PROGRESS')) return
    if (!confirm('آیا از تسویه این تراکنش (نشست به حساب) اطمینان دارید؟')) return
    setSettlingId(id)
    try {
      await apiClient.post(`/transactions/${id}/settle`)
      await loadTransactions()
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در تسویه تراکنش')
    } finally {
      setSettlingId(null)
    }
  }

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

    setDeletingId(id)
    try {
      await apiClient.delete(`/transactions/${id}`)
      await loadTransactions()
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در حذف تراکنش')
    } finally {
      setDeletingId(null)
    }
  }

  const allSelected = filteredTransactions.length > 0 && filteredTransactions.every((t) => selectedIds.has(t.id))
  const someSelected = selectedIds.size > 0
  
  // Filter selected transactions by status for actions
  const selectedDraftIds = Array.from(selectedIds).filter((id) => 
    filteredTransactions.find((t) => t.id === id)?.status === 'DRAFT'
  )
  const selectedSettledIds = Array.from(selectedIds).filter((id) => 
    (filteredTransactions.find((t) => t.id === id)?.status === 'SETTLED' || filteredTransactions.find((t) => t.id === id)?.status === 'CONFIRMED')
  )

  return (
    <>
      <PageMeta title="تراکنش‌ها | آیرون" description="لیست تراکنش‌ها" />
      <PageBreadcrumb pageTitle="تراکنش‌ها" />

      {/* Header */}
      <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
        <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_transactions">
          <Link
            to="/transactions/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="SUBMITTED">ارسال شده</option>
          <option value="CONFIRMED">تایید شده</option>
          <option value="SETTLED">تسویه شده</option>
          <option value="IN_PROGRESS">در حال پردازش</option>
        </select>
        
        {/* Method Filter */}
        <select
          value={methodFilter}
          onChange={(e) => setMethodFilter(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="TRANSFER">انتقال بانکی</option>
        </select>

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

        {/* Clear Filters */}
        {(search || statusFilter || methodFilter || fromDate || toDate) && (
          <button
            type="button"
            onClick={() => {
              setSearch('')
              setStatusFilter('')
              setMethodFilter('')
              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">
            {/* Verify - only for DRAFT transactions */}
            {selectedDraftIds.length > 0 && (
              <button
                onClick={handleBulkVerify}
                disabled={bulkVerifying || bulkDeleting}
                className="rounded-lg bg-green-500 px-4 py-2 text-sm font-medium text-white hover:bg-green-600 disabled:opacity-50"
              >
                {bulkVerifying ? 'در حال تایید...' : `تایید ${selectedDraftIds.length} مورد`}
              </button>
            )}
            <IfPermission permission="delete_transactions">
              {selectedIds.size > 0 && (
                <button
                  onClick={handleBulkDelete}
                  disabled={bulkVerifying || 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={8} showCheckbox />
        ) : filteredTransactions.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="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>
            <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
              {search || statusFilter || methodFilter || 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="transaction_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>
                  <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">به</th>
                  <SortableTh sortKey="amount" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                    مبلغ
                  </SortableTh>
                  <SortableTh sortKey="transaction_date" 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">
                {filteredTransactions.map((t) => (
                  <tr key={t.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(t.id)}
                        onChange={(checked) => handleSelectOne(t.id, checked)}
                      />
                    </td>
                    <td className="px-5 py-4 table-mobile-primary" data-label="شماره">
                      <Link to={`/transactions/${t.id}/edit`} className="text-sm font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300">
                        {t.transaction_number}
                      </Link>
                    </td>
                    <td className="px-5 py-4" data-label="از">
                      {t.from_customer ? (
                        <div>
                          <Link to={`/customers/${t.from_customer.id}`} className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90">
                            {t.from_customer.name}
                          </Link>
                          {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-5 py-4" data-label="به">
                      {t.to_customer ? (
                        <div>
                          <Link to={`/customers/${t.to_customer.id}`} className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90">
                            {t.to_customer.name}
                          </Link>
                          {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-5 py-4" data-label="مبلغ">
                      <div className="text-sm font-medium text-gray-800 dark:text-white/90">
                        {formatCurrency(t.amount)} {getCurrencyLabel()}
                      </div>
                    </td>
                    <td className="px-5 py-4 text-sm text-gray-500 dark:text-gray-400" data-label="تاریخ">
                      {t.transaction_date ? new Date(t.transaction_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(t.status)}</td>
                    <td className="px-5 py-4 table-mobile-actions">
                      <div className="flex items-center gap-1">
                        <IfPermission permission="settle_transactions">
                          {(t.status === 'DRAFT' || t.status === 'SUBMITTED' || t.status === 'IN_PROGRESS') && (
                            <button
                              type="button"
                              onClick={() => handleQuickSettle(t.id)}
                              disabled={settlingId === t.id}
                              className="rounded-lg px-2 py-1.5 text-xs font-medium text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-500/10 disabled:opacity-50 whitespace-nowrap"
                              title="تغییر وضعیت (تسویه)"
                            >
                              {settlingId === t.id ? (
                                <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-green-500 border-t-transparent" />
                              ) : (
                                'تغییر وضعیت'
                              )}
                            </button>
                          )}
                        </IfPermission>
                        <IfPermission permission="update_transactions">
                          <Link
                            to={`/transactions/${t.id}/edit`}
                            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.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                            </svg>
                          </Link>
                        </IfPermission>
                        <IfPermission permission="delete_transactions">
                          <button
                            type="button"
                            onClick={() => handleDelete(t.id)}
                            disabled={deletingId === t.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 === 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 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>
    </>
  )
}
