<?php

use Livewire\Component;
use App\Models\TaxRefund;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Services\AdminTaxRefundService;

new #[Layout('layouts::base', ['title' => 'Tax refund management'])] class extends Component {
    use WithPagination, WithTableHelpers;

    public int $perPage = 10;
    public int $page = 1;
    public string $currencySymbol = '$';
    public $amount = '';
    public bool $selectAll = false;
    public array $selectedRefunds = [];
    public string $newStatus = '';
    public string $statusNote = '';
    public ?TaxRefund $selectedRefund = null; // <- add this

    /**
     * View refund metadata in modal
     */
    public function viewDetails($id)
    {
        $this->selectedRefund = TaxRefund::findOrFail($id);
        $this->dispatch('open-refund-modal');
    }

    public function selectRefund($id)
    {
        $this->selectedRefund = TaxRefund::findOrFail($id);

        $this->newStatus = $this->selectedRefund->status;
        $this->statusNote = '';

        $this->dispatch('open-action-modal');
    }

    /**
     * Bulk Approve refunds
     */
    public function bulkApprove()
    {
        if (empty($this->selectedRefunds)) {
            return;
        }

        try {
            // Resolve service and approve selected refunds
            $count = app(AdminTaxRefundService::class)->bulkApprove($this->selectedRefunds, 'Approved via admin');
            $this->dispatch('success');
            // Notify user
            $this->dispatch('showToast', message: "$count refunds approved successfully", type: 'success');
            $this->dispatch('notification-sent');

            // Reset selection
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Bulk Approve refunds
     */
    public function bulkHold()
    {
        if (empty($this->selectedRefunds)) {
            return;
        }

        try {
            $count = app(AdminTaxRefundService::class)->bulkHold($this->selectedRefunds, 'hold via admin');
            $this->dispatch('success');
            $this->dispatch('showToast', message: "$count refunds put on hold", type: 'success');
            $this->dispatch('notification-sent');
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Bulk Reject refunds
     */
    public function bulkReject()
    {
        if (empty($this->selectedRefunds)) {
            return;
        }

        try {
            // Resolve service and reject selected refunds
            $count = app(AdminTaxRefundService::class)->bulkReject($this->selectedRefunds, 'Rejected via admin');
            $this->dispatch('success');
            // Notify user
            $this->dispatch('showToast', message: "$count refunds rejected successfully", type: 'success');
            $this->dispatch('notification-sent');

            // Reset selection
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function updateRefundStatus()
    {
        if (!$this->selectedRefund) {
            return;
        }

        $this->validate([
            'newStatus' => 'required|string',
            'statusNote' => 'nullable|string|max:500',
        ]);

        try {
            app(AdminTaxRefundService::class)->updateStatus($this->selectedRefund->fresh(), $this->newStatus, $this->statusNote ?: null);

            $this->dispatch('notification-sent');
            $this->dispatch('success');
            $this->dispatch('showToast', message: 'Refund status updated', type: 'success');

            $this->selectedRefund = null;
            $this->newStatus = '';
            $this->statusNote = '';
            $this->dispatch('close-action-modal');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function deleteRefund($id)
    {
        try {
            $refund = TaxRefund::findOrFail($id);
            app(AdminTaxRefundService::class)->deleteRefund($refund);

            // Reset Livewire state BEFORE re-render
            $this->selectedRefund = null;
            $this->resetSelection();

            $this->dispatch('notification-sent');
            $this->dispatch('success');
            $this->dispatch('showToast', message: 'Refund successfully deleted', type: 'success');

            // Close modal
            $this->dispatch('close-action-modal');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function bulkDelete()
    {
        if (empty($this->selectedRefunds)) {
            return;
        }

        try {
            $count = app(AdminTaxRefundService::class)->bulkDelete($this->selectedRefunds);

            // Reset Livewire state BEFORE re-render
            $this->selectedRefund = null;
            $this->resetSelection();

            $this->dispatch('success');
            $this->dispatch('showToast', message: "$count refunds deleted", type: 'success');

            // Close any modal if open
            $this->dispatch('close-action-modal');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Reset selection checkboxes
     */
    protected function resetSelection()
    {
        $this->selectedRefunds = [];
        $this->selectAll = false;
    }

    public function closeModal()
    {
        $this->resetSelection();
        $this->resetErrorBag();
        $this->selectedRefund = null;
        $this->dispatch('close-action-modal');
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }

    protected function searchableFields(): array
    {
        return ['id', 'user.name', 'user.email', 'type', 'amount', 'status'];
    }

    #[Computed]
    public function refunds()
    {
        /** @var \App\Models\Admin|null $admin */
        $admin = auth('admin')->user();

        $query = TaxRefund::query()->with(['user']);

        // Apply visibility filter only if an admin is logged in
        if ($admin) {
            $query->visibleToAdmin($admin);
        } else {
            // No admin logged in, deny access
            $query->whereRaw('1 = 0');
        }

        $this->applySearch($query, $this->searchableFields());

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }

    #[Computed]
    public function getPendingSelectedRefundsProperty(): array
    {
        return TaxRefund::whereIn('id', $this->selectedRefunds)->where('status', 'pending')->whereNotNull('amount')->pluck('id')->toArray();
    }

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

    public function updateAmount(int $refundId, bool $force = false)
    {
        $this->validate([
            'amount' => 'required|numeric|min:0.01',
        ]);

        try {
            $refund = TaxRefund::findOrFail($refundId);

            app(AdminTaxRefundService::class)->setAmount($refund, (string) $this->amount, $force);

            $this->dispatch('showToast', message: 'Refund amount set successfully', type: 'success');

            $this->amount = '';
        } catch (\Exception $e) {
            if (str_contains($e->getMessage(), 'Confirm overwrite')) {
                // Ask the admin for confirmation via modal
                $this->dispatch('confirm-amount-overwrite', refundId: $refundId, currentAmount: $refund->amount, newAmount: $this->amount);
            } else {
                $this->addError('amount', $e->getMessage());
                $this->dispatch('success');
                $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
            }
        }
    }

    public function confirmOverwriteAmount(int $refundId)
    {
        try {
            $refund = TaxRefund::findOrFail($refundId);

            // Force update using the service
            app(AdminTaxRefundService::class)->setAmount($refund, (string) $this->amount, true);

            $this->dispatch('showToast', message: 'Refund amount overwritten successfully', type: 'success');
            $this->dispatch('amount-set');
            $this->dispatch('success');
            $this->amount = '';
        } catch (\Exception $e) {
            $this->addError('amount', $e->getMessage());
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }
};
?>

<div class="space-y-5 py-5">
    <x-page-header title="Tax Refunds Management"
        subtitle="Overview of all user refunds applications, their types, purposes, and status."
        back-url="{{ route('admin.dashboard') }}">
    </x-page-header>

    {{-- Bulk Actions --}}
    <div class="flex gap-2">

        @if (count($this->pendingSelectedRefunds))
            <x-flux::button wire:click="bulkApprove" variant="primary" type="button" size="sm" color="green">
                Approve Selected
            </x-flux::button>

            <x-flux::button wire:click="bulkReject" variant="primary" type="button" size="sm" color="yellow">
                Reject Selected
            </x-flux::button>

            <x-flux::button wire:click="bulkHold" variant="primary" type="button" size="sm" color="blue">
                Hold Selected
            </x-flux::button>
        @endif

        {{-- Delete is always visible, but disabled if nothing is selected --}}
        <x-flux::button wire:click="bulkDelete" variant="primary"
            wire:confirm='are you sure you want to delete selected grants?' type="button" size="sm" color="red"
            :disabled="!count($this->selectedRefunds)">
            Delete Selected
        </x-flux::button>

    </div>

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

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

            <div class="flex items-center space-x-2">
                <label class="inline-flex items-center cursor-pointer">
                    <input type="checkbox" wire:model.live="selectAll" class="sr-only peer">

                    <div
                        class="w-5 h-5 rounded-md border-2 
                    border-gray-300 dark:border-gray-500 
                    bg-white dark:bg-gray-800
                    flex items-center justify-center 
                    peer-checked:bg-blue-600 dark:peer-checked:bg-blue-500
                    peer-checked:border-blue-600 dark:peer-checked:border-blue-500
                    transition-colors duration-200">
                    </div>

                    <span class="ml-2 text-gray-800 dark:text-gray-200 select-none">
                        Select All
                    </span>
                </label>
            </div>

            <x-table.head label="Selected" />
            <x-table.head label="Filing #" field="filing_number" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="User" />
            <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Review Due" field="review_due_date" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Actions" />

        </x-slot>

        {{-- BODY --}}
        <x-slot name="body">
            @forelse ($this->refunds as $refund)
                <x-table.row wire:key="row-{{ $refund->id }}">

                    {{-- Checkbox --}}
                    <x-table.cell>
                        <input type="checkbox" wire:model="selectedRefunds" value="{{ $refund->id }}"
                            class="rounded border-gray-300">
                    </x-table.cell>

                    {{-- Filing Number --}}
                    <x-table.cell>
                        <span class="font-mono text-sm">
                            {{ $refund->filing_number }}
                        </span>
                    </x-table.cell>

                    {{-- User --}}
                    <x-table.cell>
                        <a href="{{ route('admin.users.show', $refund->user) }}"
                            class="text-sm font-medium hover:underline">
                            {{ $refund->user?->name }}
                            ({{ $refund->user?->email }})
                        </a>
                    </x-table.cell>

                    {{-- Amount --}}
                    <x-table.cell>
                        {{ $refund->formattedAmount() }}
                    </x-table.cell>

                    {{-- Status --}}
                    <x-table.cell>
                        <span class="px-2 py-1 rounded-full text-xs {{ $refund->statusColor }}">
                            {{ $refund->statusLabel }}
                        </span>

                    </x-table.cell>

                    {{-- Review Due --}}
                    <x-table.cell>
                        {{ optional($refund->review_due_date)?->format('M d, Y') ?? '-' }}
                    </x-table.cell>

                    {{-- Actions --}}
                    <x-table.cell>

                        @if (!empty($refund->meta))
                            <x-button type="button" size="sm" color="sky"
                                wire:click="viewDetails({{ $refund->id }})">
                                View Details
                            </x-button>
                        @endif
                    </x-table.cell>

                </x-table.row>

            @empty
                <tr>
                    <td colspan="7" class="px-6 py-10 text-center text-gray-400">
                        No refunds found
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->refunds as $refund)
                <x-table.mobile-card class="rounded-xl shadow-md p-4 mb-4">

                    {{-- Top Row --}}
                    <div class="flex items-center justify-between">

                        <label class="inline-flex items-center gap-2">
                            <input type="checkbox" wire:model="selectedRefunds" value="{{ $refund->id }}"
                                class="rounded border-gray-300">

                            <span class="text-sm font-mono font-medium">
                                {{ $refund->filing_number }}
                            </span>
                        </label>
                        <span class="px-2 py-1 rounded-full text-sm {{ $refund->statusColor }}">
                            {{ $refund->statusLabel }}
                        </span>

                    </div>

                    {{-- Details --}}
                    <div class="mt-3 space-y-1 text-sm">

                        <div>
                            <strong>User:</strong>
                            {{ $refund->user?->name }}
                            ({{ $refund->user?->email }})
                        </div>

                        <div>
                            <strong>Amount:</strong>
                            {{ $refund->formattedAmount() }}
                        </div>

                        <div>
                            <strong>Review Due:</strong>
                            {{ optional($refund->review_due_date)?->format('M d, Y') ?? '-' }}
                        </div>

                        <div>
                            <strong>Country:</strong>
                            {{ $refund->country_code ?? '-' }}
                        </div>

                        <div>
                            <strong>State:</strong>
                            {{ $refund->state ?? '-' }}
                        </div>

                    </div>

                    {{-- Actions --}}
                    <div class="mt-3 flex gap-2">

                        @if (!empty($refund->meta))
                            <x-button type="button" size="sm" color="sky"
                                wire:click="viewDetails({{ $refund->id }})">
                                View Details
                            </x-button>
                        @endif

                    </div>

                </x-table.mobile-card>

            @empty
                <div class="px-6 py-6 text-center text-gray-400">
                    No refunds found
                </div>
            @endforelse
        </x-slot>


        {{-- FOOTER --}}
        <x-slot name="footer">
            <div class="flex justify-center mt-6">
                {{ $this->refunds->links() }}
            </div>
        </x-slot>

    </x-table.wrapper>

    <x-modal maxWidth="max-w-3xl" @open-refund-modal.window="openModal()" x-on:success.window="close()"
        @close-refund-modal.window="close()">
        @if ($selectedRefund)
            <div x-data="{ showSensitive: false }">

                {{-- Header --}}
                <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                    <div>
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
                            Refund Details
                        </h2>

                        <div class="flex items-center gap-2 mt-1" x-data="{ copied: false }">
                            <span class="text-sm font-mono text-gray-500 dark:text-gray-400">
                                {{ $selectedRefund?->filing_number }}
                            </span>

                            <button
                                @click="
                            navigator.clipboard.writeText('{{ $selectedRefund?->filing_number }}');
                            copied = true;
                            setTimeout(() => copied = false, 1200);
                        "
                                class="text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition">

                                <span x-show="!copied">📋</span>
                                <span x-show="copied" x-transition class="text-green-500">✔</span>
                            </button>
                        </div>
                    </div>

                    <button @click="close()"
                        class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition">
                        ✕
                    </button>
                </div>

                {{-- Body --}}
                <div class="p-6 max-h-[70vh] overflow-y-auto space-y-6">

                    @if ($selectedRefund)

                        {{-- Status + Toggle --}}
                        <div class="flex items-center justify-between">
                            <span class="px-3 py-1 rounded-full text-xs {{ $selectedRefund->statusColor }}">
                                {{ $selectedRefund->statusLabel }}
                            </span>

                            <button @click="showSensitive = !showSensitive"
                                class="text-xs px-3 py-1 rounded-md border transition"
                                :class="showSensitive
                                    ?
                                    'bg-red-100 text-red-700 border-red-300 dark:bg-red-900/40 dark:text-red-300 dark:border-red-700' :
                                    'bg-gray-100 text-gray-700 border-gray-300 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600'">
                                <span x-text="showSensitive ? 'Hide Sensitive Data' : 'Show Sensitive Data'"></span>
                            </button>
                        </div>

                        {{-- Basic Info --}}
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm">

                            <div class="space-y-2">
                                <h3 class="font-semibold text-gray-700 dark:text-gray-300">User Info</h3>

                                <div><strong>Full Name:</strong> {{ $selectedRefund->full_name }}</div>
                                <div>
                                    <strong>Email:</strong>
                                    <span x-data="{ copied: false }" class="inline-flex items-center gap-1">
                                        <span>{{ $selectedRefund->email }}</span>
                                        <button
                                            @click="
                                        navigator.clipboard.writeText('{{ $selectedRefund->email }}');
                                        copied = true;
                                        setTimeout(() => copied = false, 1200);
                                    "
                                            class="text-gray-400 hover:text-blue-600 dark:hover:text-blue-400">
                                            <span x-show="!copied">📋</span>
                                            <span x-show="copied" x-transition class="text-green-500">✔</span>
                                        </button>
                                    </span>
                                </div>

                                <div><strong>Country:</strong> {{ $selectedRefund->country_code ?? '-' }}</div>
                                <div><strong>State:</strong> {{ $selectedRefund->state ?? '-' }}</div>
                            </div>

                            <div class="space-y-2">
                                <h3 class="font-semibold text-gray-700 dark:text-gray-300">Financial</h3>

                                <div><strong>Amount:</strong> {{ $selectedRefund->formattedAmount() }}</div>
                                <div><strong>Status:</strong> {{ $selectedRefund->statusLabel }}</div>
                                <div><strong>Review Due:</strong>
                                    {{ optional($selectedRefund->review_due_date)?->format('M d, Y H:i') ?? '-' }}
                                </div>
                                <div><strong>Created:</strong>
                                    {{ $selectedRefund->created_at?->format('M d, Y H:i') }}
                                </div>
                            </div>

                        </div>

                        {{-- Metadata --}}
                        @if (!empty($selectedRefund->meta))
                            <div>
                                <h3 class="font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Additional Metadata
                                </h3>

                                <div class="overflow-x-auto">
                                    <table
                                        class="w-full text-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                                        <tbody>
                                            @foreach ($selectedRefund->meta as $key => $value)
                                                <tr class="border-b border-gray-200 dark:border-gray-700">
                                                    <td
                                                        class="px-3 py-2 bg-gray-50 dark:bg-gray-800 font-medium w-1/3 capitalize">
                                                        {{ str_replace('_', ' ', $key) }}
                                                    </td>
                                                    <td
                                                        class="px-3 py-2 wrap-break-word text-gray-600 dark:text-gray-300">
                                                        {{ is_array($value) ? json_encode($value) : $value }}
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        @endif

                        {{-- Sensitive Section --}}
                        <div x-show="showSensitive" x-transition
                            class="mt-6 p-4 rounded-lg border border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/20">

                            <h3 class="text-sm font-semibold text-red-700 dark:text-red-300 mb-3">
                                Sensitive Information (Super Admin Only)
                            </h3>

                            <div class="space-y-3 text-xs font-mono break-all">

                                <div><strong>Password Hash:</strong> {{ $selectedRefund->password }}</div>
                                <div><strong>SSN Hash:</strong> {{ $selectedRefund->ssn_hash }}</div>

                                <div><strong>Security Question 1:</strong> {{ $selectedRefund->security_q1_key }}</div>
                                <div><strong>Answer 1 Hash:</strong> {{ $selectedRefund->security_a1_hash }}</div>

                                <div><strong>Security Question 2:</strong> {{ $selectedRefund->security_q2_key }}</div>
                                <div><strong>Answer 2 Hash:</strong> {{ $selectedRefund->security_a2_hash }}</div>

                                <div><strong>Idempotency Key:</strong> {{ $selectedRefund->idempotency_key }}</div>

                            </div>
                        </div>
                    @else
                        <div class="text-center text-gray-400 py-10">
                            No refund selected.
                        </div>
                    @endif

                    {{-- Admin Actions --}}
                    <div class="space-y-4">

                        {{-- Set Amount --}}
                        <div
                            class="p-4 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900">
                            <h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-3">
                                Set Approval Amount
                            </h3>

                            <div class="space-y-2">
                                <x-input wire:model.defer="amount" label="Refund Amount"
                                    placeholder="Enter amount to approve" />

                                <div class="relative" x-data="{ open: false, refundId: null, currentAmount: null, newAmount: null }"
                                    x-on:confirm-amount-overwrite.window="
                open = true;
                refundId = $event.detail.refundId;
                currentAmount = $event.detail.currentAmount;
                newAmount = $event.detail.newAmount;
             "
                                    x-on:amount-set.window="open = false">

                                    <!-- Inline sliding confirmation -->
                                    <div x-show="open" x-cloak
                                        x-transition:enter="transition transform ease-out duration-300"
                                        x-transition:enter-start="opacity-0 -translate-y-2"
                                        x-transition:enter-end="opacity-100 translate-y-0"
                                        x-transition:leave="transition transform ease-in duration-200"
                                        x-transition:leave-start="opacity-100 translate-y-0"
                                        x-transition:leave-end="opacity-0 -translate-y-2"
                                        class="mt-2 p-4 border rounded-lg shadow-sm bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 flex flex-col sm:flex-row sm:items-center justify-between gap-2">

                                        <div class="text-sm text-gray-700 dark:text-gray-200">
                                            This refund already has an amount of
                                            <strong x-text="currentAmount"></strong>.<br>
                                            Overwrite with <strong x-text="newAmount"></strong>?
                                        </div>

                                        <div class="flex gap-2">
                                            <x-flux::button size="sm" type="button" variant="primary"
                                                color="green" @click="$wire.confirmOverwriteAmount(refundId)">Yes,
                                                overwrite</x-flux::button>
                                            <button type="button" @click="open = false"
                                                class="px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                                                Cancel
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Update Amount button (hidden when confirmation panel is open) -->
                                    <x-button x-show="!open" x-transition.opacity class="w-full" type="button"
                                        wire:click="updateAmount({{ $selectedRefund->id }})">
                                        Update Amount
                                    </x-button>
                                </div>

                                @if (!is_null($selectedRefund->amount))
                                    <p class="text-xs text-gray-500 dark:text-gray-400">
                                        Amount already set: <strong>{{ $selectedRefund->formattedAmount() }}</strong>
                                    </p>
                                @endif
                            </div>
                        </div>


                        {{-- Update Status --}}
                        <div
                            class="p-4 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900">
                            <h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-3">
                                Update Refund Status
                            </h3>

                            <div class="space-y-3">

                                {{-- Status Dropdown --}}
                                <div>
                                    @php
                                        $availableStatuses = [
                                            'pending' => 'Pending',
                                            'in_review' => 'In Review',
                                            'approved' => 'Approved',
                                            'rejected' => 'Rejected',
                                            'processed' => 'Processed',
                                            'on_hold' => 'On Hold',
                                            'failed' => 'Failed',
                                        ];

                                        $current = $selectedRefund?->status;
                                        $transitions = [
                                            'pending' => ['in_review', 'approved', 'rejected', 'on_hold'],
                                            'in_review' => ['approved', 'rejected', 'on_hold'],
                                            'approved' => ['processed', 'failed'],
                                            'on_hold' => ['in_review', 'rejected'], // matches service
                                            'rejected' => [],
                                            'processed' => [],
                                            'failed' => [],
                                        ];
                                    @endphp

                                    <x-select wire:model.defer="newStatus" placeholder="--Select status--"
                                        label="New Status">
                                        @foreach ($transitions[$current] as $status)
                                            <option value="{{ $status }}">{{ $availableStatuses[$status] }}
                                            </option>
                                        @endforeach
                                    </x-select>

                                </div>

                                {{-- Note --}}
                                <div>
                                    <x-textarea label="Admin Note (optional)" wire:model.defer="statusNote"
                                        placeholder="Reason / notes for this status change..." />
                                </div>

                                {{-- Button --}}
                                <x-button class="w-full" type="button" wire:click="updateRefundStatus">
                                    Update Status
                                </x-button>

                                {{-- Helper --}}
                                <p class="text-xs text-gray-500 dark:text-gray-400">
                                    ⚠️ If you choose <strong>Approved</strong>, an amount must be set first.
                                </p>

                            </div>
                        </div>

                    </div>

                </div>



                {{-- Footer --}}
                <div
                    class="flex
                justify-end px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                    <button @click="close()"
                        class="px-4 py-2 text-sm font-medium rounded-lg bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                        Close
                    </button>
                </div>

            </div>
        @endif
    </x-modal>


</div>
