<?php

use App\Models\WalletTransaction;
use App\Services\DefaultCurrencyService;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

new #[Layout('layouts.trading')] class extends Component {
    use WithPagination;

    #[Computed]
    public function currencyCode(): string
    {
        return app(DefaultCurrencyService::class)->code();
    }

    #[Computed]
    public function transactions()
    {
        return WalletTransaction::query()
            ->where('user_id', auth()->id())
            ->latest()
            ->paginate(15, ['*'], 'transactions_page');
    }

    public function canDownloadReceipt(WalletTransaction $transaction): bool
    {
        return $transaction->canDownloadReceipt();
    }
}; ?>

<div>
	@include('partials.trading.topbar', ['title' => 'Transactions'])

	<div class="space-y-3 px-4 py-4">
		<p class="text-sm font-semibold text-foreground">{{ __('Transaction') }}</p>

		@forelse ($this->transactions as $transaction)
			<div wire:key="transaction-{{ $transaction->id }}"
				class="flex items-center justify-between rounded-xl border border-border bg-card p-3">
				<div>
					<p class="text-sm font-semibold text-foreground">{{ ucfirst(str_replace('_', ' ', $transaction->type)) }}</p>
					<p class="text-xs text-muted-foreground">{{ $transaction->created_at?->format('Y-m-d H:i') }}</p>
				</div>
				<div class="text-right">
					<p class="text-sm font-semibold text-foreground">{{ $this->currencyCode }}
						{{ number_format((float) $transaction->amount, 2) }}</p>
					@php($normalizedStatus = strtolower((string) $transaction->status))
					<p
						class="text-xs text-muted-foreground transaction-status {{ $normalizedStatus === 'pending' ? 'transaction-status--pending' : ($normalizedStatus === 'rejected' ? 'transaction-status--rejected' : (in_array($normalizedStatus, ['approved', 'completed'], true) ? 'transaction-status--approved' : '')) }}">
						{{ ucfirst($transaction->status) }}
					</p>
					@if ($this->canDownloadReceipt($transaction))
						<a href="{{ route('member.transactions.receipt.print', ['transaction' => $transaction->id]) }}"
							wire:navigate
							class="mt-2 inline-flex rounded-md border border-border px-2.5 py-1 text-xs font-semibold text-foreground hover:bg-muted/60">
							{{ __('Print receipt') }}
						</a>
					@endif
				</div>
			</div>
		@empty
			<p class="text-sm text-muted-foreground">{{ __('No transactions yet.') }}</p>
		@endforelse

		@if ($this->transactions->hasPages())
			<div class="pt-1">
				{{ $this->transactions->links() }}
			</div>
		@endif
	</div>
</div>
