<x-layouts.admin :title="__('Payments')" :subtitle="__('Track all subscription payments, refunds, and failed transactions.')">
    <div class="space-y-6">

        {{-- Filter & Actions Panel --}}
        <div class="panel p-6">
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div>
                    <p class="panel-heading">{{ __('Payments') }}</p>
                    <p class="mt-2 text-sm text-muted">{{ __('Track payments, refunds, and transaction history.') }}</p>
                </div>
                <div class="flex flex-wrap items-center gap-3">
                    <button type="button" class="btn-secondary" x-data @click="$dispatch('open-modal', 'import-payments')">{{ __('Import CSV') }}</button>
                    <a href="{{ route('admin.payments.export', ['template' => 1]) }}" class="btn-secondary">{{ __('Download Template') }}</a>
                </div>
            </div>

            <form method="get" action="{{ route('admin.payments.index') }}" class="filter-form mt-6 grid gap-4 lg:grid-cols-[1.4fr_1fr_1fr_1fr_1fr_auto] md:grid-cols-[1.4fr_1fr_1fr] sm:grid-cols-2">
                <div>
                    <label class="sr-only" for="search">{{ __('Search') }}</label>
                    <input id="search" name="search" value="{{ request('search') }}" class="input-field" placeholder="{{ __('Search by invoice or user') }}">
                </div>
                <div>
                    <label class="sr-only" for="status">{{ __('Status') }}</label>
                    <select id="status" name="status" class="input-field">
                        <option value="">{{ __('All statuses') }}</option>
                        <option value="succeeded" @selected(request('status') === 'succeeded')>{{ __('Succeeded') }}</option>
                        <option value="failed" @selected(request('status') === 'failed')>{{ __('Failed') }}</option>
                        <option value="refunded" @selected(request('status') === 'refunded')>{{ __('Refunded') }}</option>
                        <option value="pending" @selected(request('status') === 'pending')>{{ __('Pending') }}</option>
                    </select>
                </div>
                <div>
                    <label class="sr-only" for="from">{{ __('From date') }}</label>
                    <input id="from" type="date" name="from" value="{{ request('from') }}" class="input-field">
                </div>
                <div>
                    <label class="sr-only" for="to">{{ __('To date') }}</label>
                    <input id="to" type="date" name="to" value="{{ request('to') }}" class="input-field">
                </div>
                <div class="flex items-center gap-3">
                    <button class="btn-secondary" type="submit">{{ __('Filter') }}</button>
                    <a href="{{ route('admin.payments.index') }}" class="btn-secondary">{{ __('Reset') }}</a>
                </div>
            </form>
        </div>

        {{-- Payments Table Panel --}}
        <div class="panel p-6" x-data="{
            view: localStorage.getItem('admin-payments-view') || 'list'
        }" x-init="$watch('view', v => localStorage.setItem('admin-payments-view', v))">
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div>
                    <p class="panel-heading">{{ __('Payment Directory') }}</p>
                    <p class="mt-2 text-sm text-muted">{{ __('Showing') }} {{ $payments->firstItem() ?? 0 }}-{{ $payments->lastItem() ?? 0 }} {{ __('of') }} {{ $payments->total() }} {{ __('transactions.') }}</p>
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <button type="button" @click="view = 'list'" :class="view === 'list' ? 'btn-primary' : 'btn-secondary'">{{ __('List') }}</button>
                    <button type="button" @click="view = 'grid'" :class="view === 'grid' ? 'btn-primary' : 'btn-secondary'">{{ __('Grid') }}</button>
                    <button type="button" class="btn-secondary" onclick="window.print()">{{ __('Print') }}</button>
                    <a href="{{ route('admin.payments.export', request()->query()) }}" class="btn-secondary">{{ __('Export') }}</a>
                </div>
            </div>

            {{-- List View --}}
            <div x-show="view === 'list'" class="mt-6 overflow-x-auto">
                <table class="w-full text-left text-sm">
                    <thead class="text-xs uppercase tracking-[0.2em] text-muted">
                        <tr>
                            <th class="pb-3">{{ __('Invoice') }}</th>
                            <th class="pb-3">{{ __('User') }}</th>
                            <th class="pb-3">{{ __('Amount') }}</th>
                            <th class="pb-3">{{ __('Status') }}</th>
                            <th class="pb-3">{{ __('Date') }}</th>
                            <th class="pb-3 text-right">{{ __('Actions') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-border/60">
                        @forelse($payments as $payment)
                        <tr>
                            <td class="py-4">
                                {{-- Show the invoice number as primary identifier (what's
                                     printed on the customer's PDF) — falls back to gateway
                                     transaction id when no invoice has been generated yet
                                     (e.g. legacy payments from before invoicing shipped). --}}
                                @if($payment->invoice_number)
                                    <code class="text-xs font-mono font-bold text-ink">{{ $payment->invoice_number }}</code>
                                @else
                                    <code class="text-xs text-muted font-mono">{{ $payment->stripe_payment_id ?? $payment->gateway_transaction_id ?? '#' . $payment->id }}</code>
                                @endif
                            </td>
                            <td class="py-4">
                                <span class="font-semibold text-ink">{{ $payment->workspace?->name ?? __('N/A') }}</span>
                            </td>
                            <td class="py-4">
                                <span class="text-sm font-semibold text-ink">{{ \App\Helpers\CurrencyHelper::formatWith((float) $payment->amount, $payment->currency) }}</span>
                            </td>
                            <td class="py-4">
                                <span class="text-sm font-semibold text-ink">{{ ucfirst($payment->status) }}</span>
                            </td>
                            <td class="py-4 text-sm text-ink">{{ $payment->created_at->format('M j, Y') }}</td>
                            <td class="py-4 text-right">
                                <div class="inline-flex items-center gap-2">
                                    {{-- Invoice actions — succeeded payments get a View
                                         (iframe modal preview, no new tab) + Download.
                                         InvoiceController allows admins through
                                         unconditionally so admin can pull any customer's
                                         invoice for support. --}}
                                    @if($payment->status === 'succeeded')
                                        {{-- Open the themed HTML preview in a new tab so
                                             the user keeps the payments list open behind it.
                                             The preview page has its own Download / Print /
                                             Close buttons in the top action bar. --}}
                                        <a href="{{ route('invoices.preview', $payment) }}" target="_blank" rel="noopener" class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold rounded-lg border border-border text-ink hover:border-brand hover:text-brand transition" title="{{ __('Preview invoice') }}">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                                            {{ __('View') }}
                                        </a>
                                        <a href="{{ route('invoices.download', $payment) }}" class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold rounded-lg bg-brand text-white hover:bg-brand-strong transition" title="{{ __('Download invoice PDF') }}">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                                            {{ __('PDF') }}
                                        </a>
                                    @endif
                                    @if($payment->status === 'succeeded' && !$payment->refund_amount)
                                        <button type="button" class="btn-danger text-xs px-3 py-1.5" x-data @click="$dispatch('open-modal', 'confirm-refund-{{ $payment->id }}')">{{ __('Refund') }}</button>
                                    @endif

                                    {{-- Manual Approve — only for Bank Transfer / Offline
                                         pending rows. Online gateways must NOT show this
                                         because their state belongs to the gateway's
                                         webhook flow; flipping their status here would
                                         skip the gateway's idempotency guarantees and
                                         risk double-activating a subscription. --}}
                                    @if($payment->status === 'pending' && in_array($payment->gateway_slug, ['bank_transfer', 'offline'], true))
                                        <button type="button" class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold rounded-lg bg-success text-white hover:bg-success/90 transition" x-data @click="$dispatch('open-modal', 'confirm-approve-{{ $payment->id }}')" title="{{ __('Approve this pending payment') }}">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                                            {{ __('Approve') }}
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>

                        {{-- Approve confirmation modal — separate from refund modal --}}
                        @if($payment->status === 'pending' && in_array($payment->gateway_slug, ['bank_transfer', 'offline'], true))
                        <x-admin-modal name="confirm-approve-{{ $payment->id }}">
                            <form method="POST" action="{{ route('admin.payments.approve', $payment->id) }}" class="p-6 space-y-4">
                                @csrf
                                <div>
                                    <p class="text-lg font-semibold text-ink">{{ __('Approve payment') }} #{{ $payment->id }}?</p>
                                    <p class="mt-2 text-sm text-muted">
                                        {{ __('Confirm you have received') }}
                                        <strong class="text-ink">{{ \App\Helpers\CurrencyHelper::formatWith((float) $payment->amount, $payment->currency) }}</strong>
                                        {{ __('via') }} <span class="capitalize">{{ str_replace('_', ' ', $payment->gateway_slug) }}</span>
                                        {{ __('from') }} {{ $payment->workspace?->name ?? __('this customer') }}.
                                    </p>
                                    <p class="mt-2 text-xs text-muted">
                                        {{ __("This will mark the payment as Succeeded, activate the customer's subscription, generate the invoice, and write an audit log entry.") }}
                                    </p>
                                </div>
                                <div class="flex justify-end gap-3">
                                    <button type="button" class="btn-secondary" x-on:click="$dispatch('close')">{{ __('Cancel') }}</button>
                                    <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-success text-white text-sm font-semibold hover:bg-success/90">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                                        {{ __('Approve Payment') }}
                                    </button>
                                </div>
                            </form>
                        </x-admin-modal>
                        @endif

                        {{-- Refund confirmation modal --}}
                        @if($payment->status === 'succeeded' && !$payment->refund_amount)
                        <x-admin-modal name="confirm-refund-{{ $payment->id }}">
                            <form method="POST" action="{{ route('admin.payments.refund', $payment->id) }}" class="p-6 space-y-4">
                                @csrf
                                <div>
                                    <p class="text-lg font-semibold text-ink">{{ __('Refund') }} {{ \App\Helpers\CurrencyHelper::formatWith((float) $payment->amount, $payment->currency) }}?</p>
                                    <p class="mt-2 text-sm text-muted">{{ __('This will issue a') }} <strong class="text-danger">{{ __('full refund') }}</strong> {{ __('of') }} {{ \App\Helpers\CurrencyHelper::formatWith((float) $payment->amount, $payment->currency) }} {{ __('to') }} {{ $payment->workspace?->name ?? __('this customer') }}. {{ __('This action cannot be undone.') }}</p>
                                </div>
                                <div class="flex justify-end gap-3">
                                    <button type="button" class="btn-secondary" x-on:click="$dispatch('close')">{{ __('Cancel') }}</button>
                                    <button type="submit" class="btn-danger">{{ __('Issue Refund') }}</button>
                                </div>
                            </form>
                        </x-admin-modal>
                        @endif
                        @empty
                        <tr>
                            <td colspan="6" class="py-6 text-center text-sm text-muted">{{ __('No payments found.') }}</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Grid View --}}
            <div x-show="view === 'grid'" x-cloak class="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                @forelse($payments as $payment)
                <div class="panel p-4 space-y-3">
                    <div class="flex items-center justify-between">
                        <span class="font-semibold text-ink">{{ $payment->workspace?->name ?? __('N/A') }}</span>
                        <span class="text-sm font-semibold text-ink">{{ \App\Helpers\CurrencyHelper::formatWith((float) $payment->amount, $payment->currency) }}</span>
                    </div>
                    <div class="flex items-center justify-between text-sm">
                        <span class="font-semibold text-ink">{{ ucfirst($payment->status) }}</span>
                        <span class="text-muted">{{ $payment->created_at->format('M j, Y') }}</span>
                    </div>
                    @if($payment->invoice_number)
                        <code class="text-xs font-mono font-bold text-ink block truncate">{{ $payment->invoice_number }}</code>
                    @else
                        <code class="text-xs text-muted font-mono block truncate">{{ $payment->stripe_payment_id ?? $payment->gateway_transaction_id ?? '#' . $payment->id }}</code>
                    @endif
                    @if($payment->status === 'succeeded')
                    <div class="pt-2 border-t border-border/60 flex items-center gap-2 flex-wrap">
                        <a href="{{ route('invoices.preview', $payment) }}" target="_blank" rel="noopener" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold rounded-lg border border-border text-ink hover:border-brand hover:text-brand transition">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                            {{ __('View') }}
                        </a>
                        <a href="{{ route('invoices.download', $payment) }}" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold rounded-lg bg-brand text-white hover:bg-brand-strong transition">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                            {{ __('PDF') }}
                        </a>
                        @if(!$payment->refund_amount)
                            <button type="button" class="btn-danger text-xs px-2.5 py-1" x-data @click="$dispatch('open-modal', 'confirm-refund-{{ $payment->id }}')">{{ __('Refund') }}</button>
                        @endif
                    </div>
                    @endif
                    {{-- Grid-view Approve button — parity with the table view
                         so admins switching between Table/Grid don't lose the
                         action. Same gating: pending + manual gateway only. --}}
                    @if($payment->status === 'pending' && in_array($payment->gateway_slug, ['bank_transfer', 'offline'], true))
                    <div class="pt-2 border-t border-border/60">
                        <button type="button" class="w-full inline-flex items-center justify-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg bg-success text-white hover:bg-success/90 transition" x-data @click="$dispatch('open-modal', 'confirm-approve-{{ $payment->id }}')">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                            {{ __('Approve Payment') }}
                        </button>
                    </div>
                    @endif
                </div>
                @empty
                <div class="col-span-full py-6 text-center text-sm text-muted">{{ __('No payments found.') }}</div>
                @endforelse
            </div>

            @if($payments->hasPages())
            <div class="mt-4 border-t border-border/60 pt-4">
                {{ $payments->withQueryString()->links() }}
            </div>
            @endif

        </div>
    </div>

    {{-- Import Modal --}}
    <x-admin-modal name="import-payments">
        <form method="POST" action="{{ route('admin.payments.import') }}" enctype="multipart/form-data" class="p-6 space-y-5">
            @csrf
            <div>
                <h3 class="text-lg font-semibold text-ink">{{ __('Import Payments') }}</h3>
                <p class="mt-1 text-sm text-muted">{{ __('Upload a CSV file that matches the provided template.') }}</p>
            </div>
            <x-file-uploader name="file" accept=".csv,.txt" :label="__('CSV File')" />
            <div class="flex justify-end gap-3">
                <button type="button" class="btn-secondary" x-on:click="$dispatch('close')">{{ __('Cancel') }}</button>
                <button type="submit" class="btn-primary">{{ __('Upload') }}</button>
            </div>
        </form>
    </x-admin-modal>
</x-layouts.admin>
