<?php

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Models\Transaction;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use App\Support\Currency;
use App\Services\ExportService;
use App\Models\Admin;
use Livewire\Attributes\Layout;

new #[Layout('layouts::base')] class extends Component {
    use WithPagination, WithTableHelpers;

    // Pagination
    public int $perPage = 10;
    public int $page = 1;

    // Export settings
    public string $exportFormat = 'csv'; // csv | xlsx | pdf
    public string $exportDelivery = 'download'; // download | email
    public string $exportScope = 'page'; // page | all

    // Selected transaction for receipt modal
    public ?Transaction $selectedTransaction = null;
    public ?string $modalMessage = null;
    public ?string $receiptModalMessage = null;

    // Currency
    public string $currencySymbol = '$';
    public array $selected = [];
    public bool $selectAll = false;

    // Admin: user whose transactions we are fetching
    public User $user;

    protected ExportService $exportService;

    protected function exportService(): ExportService
    {
        return $this->exportService;
    }

    /**
     * Searchable fields
     */
    protected function searchableFields(): array
    {
        return ['id', 'type', 'amount', 'status'];
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->reset(['selected', 'selectAll']);
        $this->dispatch('perPageUpdated', value: $this->perPage);
    }

    public function mount(User $user, ExportService $exportService)
    {
        $this->user = $user;
        $this->exportService = $exportService;

        $profile = $this->user->profile;
        $this->currencySymbol = $profile ? Currency::symbol($profile->currency) : '$';
    }

    /**
     * Base query scoped to the passed user
     */
    protected function baseQuery()
    {
        $profile = $this->user->profile;

        if (!$profile) {
            return Transaction::query()->whereRaw('1=0'); // no transactions
        }

        return Transaction::query()
            ->whereIn('account_id', $profile->accounts()->pluck('id'))
            ->with(['account', 'transfer.paymentMethod', 'cryptoBalance'])
            ->tap(fn($q) => $this->applySearch($q, $this->searchableFields()))
            ->orderBy($this->sortField, $this->sortDirection);
    }

    /**
     * Paginated transactions
     */
    #[Computed]
    public function transactions()
    {
        return $this->baseQuery()->paginate($this->perPage);
    }

    public function deleteTransaction(string $transactionId)
    {
        $transaction = $this->baseQuery()->where('id', $transactionId)->firstOrFail();

        $transaction->delete();

        $this->resetPage();

        $this->dispatch('showToast', message: 'Transaction deleted successfully', type: 'success');
    }

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selected = $this->transactions->pluck('id')->toArray();
        } else {
            $this->selected = [];
        }
    }

    public function bulkDelete()
    {
        $this->baseQuery()->whereIn('id', $this->selected)->delete();

        $this->reset(['selected', 'selectAll']);
        $this->resetPage();

        $this->dispatch('showToast', message: 'Selected transactions deleted', type: 'success');
    }

    #[Computed]
    public function transactionFields(): array
    {
        if (!$this->selectedTransaction) {
            return [];
        }

        $t = $this->selectedTransaction;
        $symbol = $this->currencySymbol ?? '$';

        $fields = [['label' => 'Transaction ID', 'value' => $t->id], ['label' => 'Transaction Ref', 'value' => $t->transaction_ref], ['label' => 'Type', 'value' => ucfirst(str_replace('_', ' ', $t->type))], ['label' => 'Status', 'value' => ucfirst($t->statusLabel() ?? $t->status)], ['label' => 'Amount', 'value' => $symbol . number_format((float) ($t->amount ?? 0), $t->crypto_balance_id ? 8 : 2)], ['label' => 'Post Balance', 'value' => $symbol . number_format((float) ($t->balance_after ?? 0), 2)], ['label' => 'Customer', 'value' => $t->customerName() ?? 'N/A'], ['label' => 'Account', 'value' => $t->maskedAccount() ?? 'N/A'], ['label' => 'Date', 'value' => $t->created_at->toDayDateTimeString() ?? 'N/A']];

        switch ($t->type) {
            case 'withdrawal':
                if ($t->withdrawal_id) {
                    $fields[] = ['label' => 'Withdrawal ID', 'value' => $t->withdrawal_id];
                }
                if ($t->method) {
                    $fields[] = ['label' => 'Method', 'value' => ucfirst($t->method)];
                }
                if ($t->description) {
                    $fields[] = ['label' => 'Description', 'value' => $t->description];
                }
                break;
            case 'deposit':
                if ($t->deposit_id) {
                    $fields[] = ['label' => 'Deposit ID', 'value' => $t->deposit_id];
                }
                if ($t->method) {
                    $fields[] = ['label' => 'Method', 'value' => ucfirst($t->method)];
                }
                break;
            case 'loan':
                if ($t->loan_id) {
                    $fields[] = ['label' => 'Loan ID', 'value' => $t->loan_id];
                }
                if ($t->description) {
                    $fields[] = ['label' => 'Description', 'value' => $t->description];
                }
                break;
            case 'crypto':
                if ($t->crypto_balance_id) {
                    $fields[] = ['label' => 'Crypto Balance ID', 'value' => $t->crypto_balance_id];
                }
                if ($t->description) {
                    $fields[] = ['label' => 'Description', 'value' => $t->description];
                }
                break;
            case 'transfer':
                if ($t->transfer?->type) {
                    $fields[] = ['label' => 'Transfer Type', 'value' => ucfirst($t->transfer->type)];
                }
                break;
        }

        return $fields;
    }

    #[Computed]
    public function transferFields(): array
    {
        if (!$this->selectedTransaction || !str_contains($this->selectedTransaction->type, 'transfer')) {
            return [];
        }

        $transfer = $this->selectedTransaction->transfer;
        if (!$transfer) {
            return [];
        }

        $meta = $transfer->meta ?? [];
        $fields = [];

        $paymentMethod = \App\Models\PaymentMethod::find($transfer->payment_method_id);
        $configFields = $paymentMethod?->fields['fields'] ?? [];

        foreach ($configFields as $field) {
            $name = $field['name'] ?? null;
            $label = $field['label'] ?? $name;
            if (!$name) {
                continue;
            }

            $value = $meta[$name] ?? null;
            if (($field['type'] ?? '') === 'file') {
                $fields[] = ['label' => $label, 'value' => $value ? 'Uploaded' : 'N/A'];
                continue;
            }

            $fields[] = ['label' => $label, 'value' => $value ?: 'N/A'];
        }

        return $fields;
    }

    #[Computed]
    public function transferFee(): string
    {
        if (!$this->selectedTransaction || !str_contains($this->selectedTransaction->type, 'transfer')) {
            return '';
        }
        $fee = $this->selectedTransaction->transfer->fee ?? 0;
        return ($this->currencySymbol ?? '$') . number_format((float) $fee, 2);
    }

    #[Computed]
    public function transferTotal(): string
    {
        if (!$this->selectedTransaction || !str_contains($this->selectedTransaction->type, 'transfer')) {
            return '';
        }
        $total = $this->selectedTransaction->transfer->total ?? 0;
        return ($this->currencySymbol ?? '$') . number_format((float) $total, 2);
    }

    public function openReceiptModal(int $transactionId)
    {
        $this->selectedTransaction = null;
        /** @var \App\Models\Transaction $transaction */
        $transaction = Transaction::with(['transfer.paymentMethod', 'account', 'cryptoBalance'])
            ->where('id', $transactionId)
            ->whereIn('account_id', $this->user->profile->accounts()->pluck('id')->toArray())
            ->firstOrFail();

        $this->selectedTransaction = $transaction;
        $this->dispatch('open-transaction-modal');
    }

    public function closeReceiptModal()
    {
        $this->dispatch('close-transaction-modal');
        $this->selectedTransaction = null;
        $this->receiptModalMessage = null;
    }

    public function clearModalMessage()
    {
        $this->modalMessage = null;
    }

    /**
     * Export transactions (download or email)
     */
    public function export()
    {
        $transactions = $this->exportScope === 'page' ? $this->transactions->getCollection() : $this->baseQuery()->get();

        if ($transactions->isEmpty()) {
            $this->dispatch('showToast', message: 'No data to export.', type: 'warning');
            return;
        }

        if ($this->exportFormat === 'pdf' && $this->exportScope === 'all') {
            $this->exportScope = 'page';
        }

        if ($this->exportDelivery === 'download') {
            return $this->exportService()->download($transactions, $this->exportFormat, 'transactions', pdfTitle: 'Transactions Export');
        }

        $this->exportService()->email(
            $transactions,
            $this->exportFormat,
            'transactions',
            $this->user->email, // send to user email
            pdfTitle: 'Transactions Export',
        );

        $this->dispatch('showToast', message: 'Export emailed successfully.', type: 'success');
    }

    protected function generateReceiptPdf(): \Barryvdh\DomPDF\PDF
    {
        if (!$this->selectedTransaction) {
            throw new \RuntimeException('No transaction selected.');
        }

        return Pdf::loadView('exports.transaction_receipt', [
            'transaction' => $this->selectedTransaction,
            'fields' => $this->transactionFields,
            'currencySymbol' => $this->currencySymbol ?? '$',
            'transferFields' => $this->transferFields,
            'transferFee' => $this->transferFee,
            'transferTotal' => $this->transferTotal,
        ]);
    }

    public function downloadReceipt()
    {
        $pdf = $this->generateReceiptPdf();
        $filename = 'receipt-' . $this->selectedTransaction->id . '.pdf';

        return response()->streamDownload(fn() => print $pdf->output(), $filename);
    }

    public function emailReceipt()
    {
        if (!$this->selectedTransaction) {
            $this->receiptModalMessage = 'No transaction selected.';
            return;
        }

        // Get the currently logged-in admin via the 'admin' guard
        $admin = auth('admin')->user();
        if (!$admin) {
            $this->receiptModalMessage = 'No admin logged in.';
            return;
        }

        // Ensure exports folder exists
        Storage::disk('local')->makeDirectory('exports');

        $filename = 'receipt-' . $this->selectedTransaction->id . '.pdf';
        $relativePath = 'exports/' . $filename;
        $fullPath = Storage::disk('local')->path($relativePath);

        // Generate PDF
        $pdf = $this->generateReceiptPdf();
        file_put_contents($fullPath, $pdf->output());

        if (!file_exists($fullPath)) {
            $this->receiptModalMessage = 'Receipt file was not created.';
            return;
        }

        // Send email to admin
        Mail::send(
            'emails.receipt',
            ['user' => $this->user], // optional: include info of the target user
            function ($message) use ($admin, $fullPath, $filename) {
                $message
                    ->to($admin->email)
                    ->subject('Transaction Receipt')
                    ->attach($fullPath, [
                        'as' => $filename,
                        'mime' => 'application/pdf',
                    ]);
            },
        );

        // Cleanup
        Storage::disk('local')->delete($relativePath);

        $this->dispatch('showToast', message: 'Receipt emailed successfully to admin.', type: 'success');
        $this->dispatch('success-email');
    }

    public function triggerExport()
    {
        $this->dispatch('open-export-modal');
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || User Transaction History
</x-slot:title>
<div class="py-3">
    <x-page-header title="{{ $this->user->name }}'s Transaction History"
        subtitle="View all transactions, including amounts, status, and timestamps." rightText="Back to User"
        back-url="{{ route('admin.users.show', $this->user) }}">
    </x-page-header>
    <div>

        <x-modal maxWidth="max-w-4xl" @open-transaction-modal.window="openModal()"
            @close-transaction-modal.window="close()" x-on:success-email.window="close()">

            <div class="bg-gray-50 text-gray-900 relative leading-relaxed">

                <!-- Watermark -->
                <div class="absolute inset-0 flex items-center justify-center pointer-events-none">
                    <span class="text-[9rem] font-extrabold tracking-widest text-gray-200/40 rotate-[-30deg]">
                        RECEIPT
                    </span>
                </div>

                <!-- Content -->
                <div class="relative p-10 space-y-8">

                    <!-- Header -->
                    <div class="flex justify-between items-start">
                        <div>
                            <h1 class="text-2xl font-bold tracking-tight">
                                Transaction Receipt
                            </h1>
                            <p class="text-sm text-gray-500 mt-1">
                                Official transaction record
                            </p>
                        </div>

                        <!-- Status -->
                        @php
                            $status = $selectedTransaction?->status ?? '';
                            $statusClass = match ($status) {
                                'completed', 'approved' => 'border-green-600 text-green-700',
                                'pending' => 'border-yellow-500 text-yellow-700',
                                'rejected' => 'border-red-600 text-red-700',
                                default => 'border-gray-400 text-gray-600',
                            };
                        @endphp

                        <span class="px-4 py-1 text-sm font-semibold border {{ $statusClass }}">
                            {{ $selectedTransaction?->statusLabel() ?? '' }}
                        </span>
                    </div>

                    <!-- Amount -->
                    @foreach ($this->transactionFields as $field)
                        @if ($field['label'] === 'Amount')
                            <div class="border-y border-gray-300 py-6 text-center">
                                <p class="text-xs uppercase tracking-widest text-gray-500">
                                    Transaction Amount
                                </p>
                                <p
                                    class="mt-2 text-4xl font-extrabold tabular-nums
                            {{ str_contains($field['value'], '+') ? 'text-green-700' : '' }}
                            {{ str_contains($field['value'], '-') ? 'text-red-700' : '' }}">
                                    {{ $field['value'] }}
                                </p>
                            </div>
                        @endif
                    @endforeach

                    <!-- Details -->
                    <div class="space-y-3">
                        @foreach ($this->transactionFields as $field)
                            @if ($field['label'] !== 'Amount')
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600">
                                        {{ $field['label'] }}
                                    </span>
                                    <span class="font-medium tabular-nums">
                                        {{ $field['value'] }}
                                    </span>
                                </div>
                            @endif
                        @endforeach
                    </div>

                    <!-- Transfer Section -->
                    @if (str_contains($selectedTransaction?->type ?? '', 'transfer') && count($this->transferFields))
                        <div class="pt-6 border-t border-gray-300 space-y-4">

                            @php
                                $transferType = $selectedTransaction->transfer->type ?? '';
                            @endphp

                            <div class="flex justify-between items-center">
                                <h2 class="text-lg font-semibold">
                                    Transfer Information
                                </h2>
                                <span class="text-xs uppercase tracking-widest text-gray-500">
                                    {{ ucfirst($transferType) }}
                                </span>
                            </div>

                            <div class="space-y-2">
                                @foreach ($this->transferFields as $field)
                                    <div class="flex justify-between text-sm">
                                        <span class="text-gray-600">
                                            {{ $field['label'] }}
                                        </span>
                                        <span class="font-medium">
                                            {{ $field['value'] }}
                                        </span>
                                    </div>
                                @endforeach
                            </div>

                            <div class="pt-4 border-t border-gray-300 space-y-2 text-sm">
                                <div class="flex justify-between">
                                    <span>Fee</span>
                                    <span class="font-semibold tabular-nums">
                                        {{ $this->transferFee }}
                                    </span>
                                </div>
                                <div class="flex justify-between font-bold text-emerald-800">
                                    <span>Total Debited</span>
                                    <span class="tabular-nums">
                                        {{ $this->transferTotal }}
                                    </span>
                                </div>
                            </div>

                        </div>
                    @endif

                    <!-- Footer -->
                    <div class="pt-8 border-t border-gray-300 text-xs text-gray-500 space-y-3">
                        @if ($receiptModalMessage)
                            <p class="text-center">
                                {{ $receiptModalMessage }}
                            </p>
                        @endif

                        <p class="text-center">
                            This receipt is system-generated and valid without a signature.
                        </p>
                    </div>

                    <!-- Actions (hidden in print/PDF if you want) -->
                    <div class="pt-6 flex gap-4 print:hidden">
                        <x-button wire:click="downloadReceipt" class="w-full">
                            Download PDF
                        </x-button>
                        <x-button wire:click="emailReceipt" class="w-full">
                            Email Receipt
                        </x-button>
                    </div>

                    <button wire:click="closeReceiptModal"
                        class="block w-full text-center text-sm text-gray-500 hover:underline mt-4 print:hidden">
                        Close
                    </button>

                </div>
            </div>
        </x-modal>

        <x-table.wrapper :items="$this->transactions">

            {{-- SEARCH --}}
            <x-slot name="search">
                <div class="flex items-center justify-between gap-4">
                    <div class="flex items-center gap-2">
                        <div>
                            <input type="checkbox" wire:model.live="selectAll">
                        </div>
                        @if (count($this->selected))
                            <div class="flex gap-2">

                                <x-flux::button type="button" variant="danger" wire:click="bulkDelete" size="sm"
                                    icon="trash"
                                    wire:confirm="are you sure you want to delete this selected transaction?">
                                    Delete Selected
                                </x-flux::button>

                            </div>
                        @endif
                    </div>
                    <div class="w-full md:w-1/3">
                        <div class="relative">
                            <x-flux::icon.magnifying-glass
                                class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />

                            <input type="text" wire:model.live="search" placeholder="Search notifications..."
                                class="w-full pl-10 pr-4 py-2 text-sm rounded-md bg-white dark:bg-gray-800 
                               border border-gray-300 dark:border-gray-700 
                               text-gray-900 dark:text-gray-100 
                               placeholder-gray-400 dark:placeholder-gray-500 
                               focus:outline-none focus:ring-2 focus:ring-sky-600 
                               focus:border-sky-600 transition" />
                        </div>
                    </div>

                </div>
            </x-slot>


            {{-- HEADERS --}}
            <x-slot name="head">

                <x-table.head label="" />
                <x-table.head label="Transaction ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Type" field="type" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Post Balance" field="balance_after" sortable :sortField="$sortField"
                    :sortDirection="$sortDirection" />
                <x-table.head label="Created At" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Action" />
            </x-slot>

            <x-slot name="body">
                @forelse ($this->transactions as $transaction)
                    <x-table.row wire:key="row-{{ $transaction->id }}"
                        class="hover:shadow-lg transition-shadow duration-200 rounded-lg mb-2">
                        <x-table.cell>
                            <input type="checkbox" value="{{ $transaction->id }}" wire:model.live="selected">
                        </x-table.cell>
                        <x-table.cell class="font-semibold text-gray-900 dark:text-gray-200">
                            #{{ $transaction->id }}
                        </x-table.cell>

                        <x-table.cell class="capitalize text-gray-700 dark:text-gray-300">
                            {{ str_replace('_', ' ', $transaction->type) }}
                        </x-table.cell>

                        <x-table.cell>
                            @php
                                $statusGradient = match ($transaction->status) {
                                    'completed' => 'bg-gradient-to-r from-green-400 to-green-600 text-white',
                                    'approved' => 'bg-gradient-to-r from-green-400 to-green-600 text-white',
                                    'pending' => 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-black',
                                    'rejected' => 'bg-gradient-to-r from-red-400 to-red-600 text-white',
                                    default => 'bg-gray-300 text-gray-800',
                                };
                            @endphp
                            <span class="px-3 py-1 rounded-full text-xs font-semibold {{ $statusGradient }}">
                                {{ str_replace('_', ' ', ucfirst($transaction->status)) }}
                            </span>
                        </x-table.cell>

                        <x-table.cell class="font-semibold">
                            @php
                                $amountClass = match ($transaction->type) {
                                    'deposit',
                                    'credit',
                                    'swap_credit',
                                    'income'
                                        => 'text-green-600 dark:text-green-400', // brighter green
                                    'withdrawal',
                                    'debit',
                                    'swap_debit',
                                    'payment'
                                        => 'text-rose-600 dark:text-rose-400', // richer red
                                    'transfer_out' => 'text-cyan-600 dark:text-cyan-400', // modern cyan
                                    'transfer_in' => 'text-teal-600 dark:text-teal-400', // deeper teal
                                    'referral_bonus' => 'text-lime-500 dark:text-lime-400', // subtle emerald
                                    'signup_bonus' => 'text-fuchsia-500 dark:text-fuchsia-400', // standout fuchsia
                                    default => 'text-gray-800 dark:text-gray-300', // clean neutral
                                };
                            @endphp
                            <span class="{{ $amountClass }}">
                                {{ $currencySymbol ?? '$' }}{{ number_format($transaction->amount, 2) }}
                            </span>
                        </x-table.cell>

                        <x-table.cell class="font-medium text-gray-700 dark:text-gray-300">
                            {{ $currencySymbol ?? '$' }}{{ number_format($transaction->balance_after, 2) }}
                        </x-table.cell>

                        <x-table.cell class="text-gray-500 dark:text-gray-400 text-sm">
                            <span title="{{ $transaction->created_at->toDayDateTimeString() }}">
                                {{ $transaction->created_at->diffForHumans() }}
                            </span>
                        </x-table.cell>

                        <x-table.cell>
                            <x-flux::button wire:click="openReceiptModal({{ $transaction->id }})" variant="primary"
                                color="sky" type="button" size="sm" icon="newspaper">
                                View Receipt
                            </x-flux::button>

                            <x-flux::button type="button" variant="danger"
                                wire:click="deleteTransaction('{{ $transaction->id }}')" size="sm"
                                icon="trash" wire:confirm="are you sure you want to delete this transaction?">
                                Delete
                            </x-flux::button>
                        </x-table.cell>

                    </x-table.row>
                @empty
                    <tr>
                        <td colspan="8" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                            <div class="flex flex-col items-center justify-center gap-2">
                                <div
                                    class="w-14 h-14 rounded-full flex items-center justify-center bg-linear-to-r from-sky-400 to-sky-600 text-white">
                                    <flux:icon name="inbox" class="w-6 h-6" />
                                </div>
                                <p class="text-gray-700 dark:text-gray-300 text-lg font-medium">No transactions
                                    found
                                </p>
                            </div>
                        </td>
                    </tr>
                @endforelse
            </x-slot>

            <x-slot name="mobile">
                @forelse ($this->transactions as $transaction)
                    <x-table.mobile-card
                        class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 mb-4 hover:shadow-xl transition duration-200">

                        <div class="flex justify-between items-center mb-3">
                            <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-200">Transaction
                                #{{ $transaction->id }}</h3>
                            <span
                                class="text-xs font-semibold px-3 py-1 rounded-full
                                            {{ $transaction->status === 'approved'
                                                ? 'bg-linear-to-r from-green-400 to-green-600 text-white'
                                                : ($transaction->status === 'pending'
                                                    ? 'bg-linear-to-r from-yellow-400 to-yellow-500 text-black'
                                                    : ($transaction->status === 'rejected'
                                                        ? 'bg-linear-to-r from-red-400 to-red-600 text-white'
                                                        : 'bg-gray-300 text-gray-800')) }}">
                                {{ str_replace('_', ' ', $transaction->status) }}
                            </span>
                        </div>

                        <div class="space-y-2 text-sm text-gray-700 dark:text-gray-300">
                            <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Type:</span>
                                <span class="capitalize">{{ str_replace('_', ' ', $transaction->type) }}</span>
                            </div>

                            <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Amount:</span>
                                @php
                                    $amountClass = match ($transaction->type) {
                                        'deposit', 'credit', 'income' => 'text-green-600 dark:text-green-400',
                                        'withdrawal', 'debit', 'payment' => 'text-red-600 dark:text-red-400',
                                        'transfer' => 'text-sky-600 dark:text-sky-400',
                                        default => 'text-gray-700 dark:text-gray-300',
                                    };
                                @endphp
                                <span class="{{ $amountClass }}">
                                    {{ $currencySymbol ?? '$' }}{{ number_format($transaction->amount, 2) }}
                                </span>
                            </div>

                            <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Post Balance:</span>
                                <span
                                    class="font-medium">{{ $currencySymbol ?? '$' }}{{ number_format($transaction->balance_after, 2) }}</span>
                            </div>

                            <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Date:</span>
                                <span class="font-medium"
                                    title="{{ $transaction->created_at->toDayDateTimeString() }}">
                                    {{ $transaction->created_at->diffForHumans() }}
                                </span>
                            </div>
                        </div>

                        <x-flux::button wire:click="openReceiptModal({{ $transaction->id }})" size="sm"
                            variant="primary" color="sky" type="button" icon="newspaper">
                            View Receipt
                        </x-flux::button>


                        <x-flux::button type="button" variant="danger"
                            wire:click="deleteTransaction('{{ $transaction->id }}')" size="sm" icon="trash"
                            wire:confirm="are you sure you want to delete this transaction?">
                            Delete
                        </x-flux::button>

                    </x-table.mobile-card>
                @empty
                    <div class="px-6 py-6 text-center text-gray-400 dark:text-gray-500">
                        No transactions found
                    </div>
                @endforelse
            </x-slot>

            {{-- Footer (pagination + perPage dropdown) --}}
            <x-slot name="footer">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4 mt-6"
                    x-data="{
                        open: false,
                        options: [5, 10, 15, 20, 25, 50],
                        selected: @js($perPage)
                    }" x-init="$watch('selected', value => $wire.set('perPage', value));
                    Livewire.on('perPageUpdated', event => selected = event.value);"
                    x-transition:enter="transition-opacity ease-out duration-500" x-transition:enter-start="opacity-0"
                    x-transition:enter-end="opacity-100" x-transition:leave="transition-opacity ease-in duration-300"
                    x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">

                    <!-- Rows Per Page Selector -->
                    <div class="relative text-sm w-fit">
                        <label class="block text-gray-700 dark:text-gray-300 mb-1 text-xs font-medium">
                            Rows per page
                        </label>

                        <button @click="open = !open"
                            class="w-36 bg-white dark:bg-gray-800 text-gray-800 dark:text-white border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 flex justify-between items-center shadow-sm hover:border-gray-400 dark:hover:border-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-500"
                            type="button" aria-haspopup="listbox" aria-expanded="open">
                            <span x-text="selected"></span>
                            <svg class="w-4 h-4 ml-2 transform transition-transform duration-200"
                                :class="{ 'rotate-180': open }" fill="none" viewbox="0 0 24 24"
                                stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>

                        <!-- Dropdown -->
                        <div x-show="open" @click.outside="open = false"
                            x-transition:enter="transition ease-out duration-100"
                            x-transition:enter-start="opacity-0 scale-95"
                            x-transition:enter-end="opacity-100 scale-100"
                            x-transition:leave="transition ease-in duration-75"
                            x-transition:leave-start="opacity-100 scale-100"
                            x-transition:leave-end="opacity-0 scale-95"
                            class="absolute bottom-0 mt-2 w-full z-50 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg">
                            <ul class="py-1 max-h-60 overflow-auto text-sm text-gray-800 dark:text-white">
                                <template x-for="option in options" :key="option">
                                    <li>
                                        <a href="#" @click.prevent="selected = option; open = false"
                                            class="block px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700"
                                            :class="{ 'bg-gray-100 dark:bg-gray-700 font-semibold': selected === option }"
                                            x-text="option"></a>
                                    </li>
                                </template>
                            </ul>
                        </div>
                    </div>

                    <!-- Pagination Links -->
                    <div class="w-full md:w-auto text-center">{{ $this->transactions->links() }}
                    </div>

                </div>

            </x-slot>

        </x-table.wrapper>
    </div>
</div>
