<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Models\Deposit;

new #[Layout('layouts::base', ['title' => 'Manage Deposits'])] class extends Component {
    use WithPagination, WithTableHelpers;
    public $perPage = 10;
    public int $page = 1;
    public string $currencySymbol = '$';

    protected function searchableFields(): array
    {
        return ['id', 'account.profile.user.name', 'account.profile.user.email', 'amount', 'created_at', 'status', 'charge', 'total'];
    }

    public function delete($id)
    {
        Deposit::findOrFail($id)->delete();
        $this->dispatch('showToast', message: 'Deposit successfully deleted', type: 'success');
    }
    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }
    #[Computed]
    public function deposits()
    {
        /** @var \App\Models\Admin|null $admin */
        $admin = auth('admin')->user();

        $query = Deposit::query();

        // 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();
    }
};
?>

<div class="space-y-5 py-5">
    <x-page-header title="Deposits Management"
        subtitle="Overview of all user deposits, their statuses, payment methods, and transaction history."
        back-url="{{ route('admin.dashboard') }}">
    </x-page-header>

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

        {{-- SEARCH --}}
        <x-slot name="search">
            <div class="flex items-center justify-between gap-4">
                <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 by name or email"
                            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="Deposit ID" field="id" 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="Charge" field="charge" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Total" field="total" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Joined" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        {{-- BODY (DESKTOP) --}}
        <x-slot name="body">
            @forelse ($this->deposits as $deposit)
                @php
                    $account = $deposit->account;
                    $profile = $account?->profile;
                    $user = $profile?->user;

                    $profilePhoto = $profile?->profile_photo
                        ? Storage::disk('public')->url($profile->profile_photo)
                        : 'https://via.placeholder.com/40';

                    $currencySymbol = $profile ? \App\Support\Currency::symbol($profile->currency) : '$';
                @endphp

                <x-table.row wire:key="row-{{ $deposit->id }}"
                    class="hover:shadow-lg transition-shadow duration-200 rounded-lg mb-2">

                    {{-- Deposit ID --}}
                    <x-table.cell>{{ $deposit->id ?? '_' }}</x-table.cell>

                    {{-- User --}}
                    <x-table.cell>
                        <a href="{{ route('admin.users.show', $user) }}" class="flex items-center gap-2">
                            @if ($profilePhoto && $profilePhoto !== 'https://via.placeholder.com/40')
                                <img src="{{ $profilePhoto }}" alt="User Avatar" class="w-6 h-6 rounded-full">
                            @else
                                <span
                                    class="w-6 h-6 flex items-center justify-center rounded-full bg-gray-300 text-gray-700 font-medium">
                                    {{ $user->initials() ?: '?' }}
                                </span>
                            @endif
                            <span>{{ $user->name ?? '-' }}</span>
                        </a>
                    </x-table.cell>



                    {{-- Amount --}}
                    <x-table.cell>
                        {{ $account ? $currencySymbol : '-' }}{{ $account ? number_format($deposit->amount, 2) : '-' }}
                    </x-table.cell>

                    {{-- Charge --}}
                    <x-table.cell>
                        {{ $account ? $currencySymbol : '-' }}{{ $account ? number_format($deposit->charge, 2) : '-' }}
                    </x-table.cell>

                    {{-- Total --}}
                    <x-table.cell>
                        {{ $account ? $currencySymbol : '-' }}{{ $account ? number_format($deposit->total, 2) : '-' }}
                    </x-table.cell>

                    {{-- Status --}}
                    <x-table.cell>
                        @if ($deposit->status === Deposit::STATUS_APPROVED)
                            <span class="px-2 py-1 rounded-full bg-green-500 text-white text-xs">Approved</span>
                        @elseif ($deposit->status === Deposit::STATUS_REJECTED)
                            <span class="px-2 py-1 rounded-full bg-red-500 text-white text-xs">Rejected</span>
                        @else
                            <span class="px-2 py-1 rounded-full bg-yellow-400 text-black text-xs">Pending</span>
                        @endif
                    </x-table.cell>

                    {{-- Joined --}}
                    <x-table.cell>{{ $deposit->created_at->diffForHumans() }}</x-table.cell>

                    {{-- Actions --}}
                    <x-table.cell>
                        <a href="{{ route('admin.deposit.show', parameters: $deposit) }}"
                            class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition">
                            Edit
                        </a>

                        <button x-data
                            @click.prevent="if (confirm('Are you sure you want to delete this deposit?')) { $wire.delete({{ $deposit->id }}) }"
                            class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-1 transition">
                            Delete
                        </button>
                    </x-table.cell>

                </x-table.row>
            @empty
                <tr>
                    <td colspan="9" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                        No deposits found
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->deposits as $deposit)
                @php
                    $account = $deposit->account;
                    $profile = $account?->profile;
                    $user = $profile?->user;

                    $profilePhoto = $profile?->profile_photo
                        ? Storage::disk('public')->url($profile->profile_photo)
                        : 'https://via.placeholder.com/40';

                    $currencySymbol = $profile ? \App\Support\Currency::symbol($profile->currency) : '$';
                @endphp


                <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">

                    {{-- User --}}
                    <a href="{{ route('admin.users.show', $user) }}" class="flex items-center gap-2">
                        @if ($profilePhoto && $profilePhoto !== 'https://via.placeholder.com/40')
                            <img src="{{ $profilePhoto }}" alt="User Avatar" class="w-6 h-6 rounded-full">
                        @else
                            <span
                                class="w-8 h-8 aspect-square flex items-center justify-center rounded-full bg-gray-300 text-gray-700 font-semibold uppercase">
                                {{ $user->initials() ?: '?' }}
                            </span>
                        @endif
                        <div class="flex flex-col">
                            <span class="font-semibold text-gray-900 dark:text-gray-200">{{ $user->name }}</span>
                            <span class="text-gray-500 dark:text-gray-400 truncate text-sm">{{ $user->email }}</span>
                        </div>
                    </a>

                    {{-- Details --}}
                    <div class="flex flex-col text-sm text-gray-700 dark:text-gray-300 space-y-1">
                        <div class="flex justify-between">
                            <span>Balance:</span>
                            <span>{{ $account ? $currencySymbol : '-' }}{{ $account ? number_format($account->available_balance, 2) : '-' }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Amount:</span>
                            <span>{{ $currencySymbol }}{{ number_format($deposit->amount, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Total:</span>
                            <span>{{ $currencySymbol }}{{ number_format($deposit->total, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Status:</span>
                            @php
                                $statusClasses = match ($deposit->status) {
                                    Deposit::STATUS_APPROVED => 'bg-green-100 text-green-800',
                                    Deposit::STATUS_REJECTED => 'bg-red-100 text-red-800',
                                    default => 'bg-yellow-100 text-yellow-800',
                                };

                                $statusText = match ($deposit->status) {
                                    Deposit::STATUS_APPROVED => 'Approved',
                                    Deposit::STATUS_REJECTED => 'Rejected',
                                    default => 'Pending',
                                };
                            @endphp

                            <span
                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses }}">
                                {{ $statusText }}
                            </span>

                        </div>
                        <div class="flex justify-between">
                            <span>Joined:</span>
                            <span>{{ $deposit->created_at->diffForHumans() }}</span>
                        </div>
                    </div>

                    {{-- Actions --}}
                    <div class="mt-3 flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0">
                        <a href="{{ route('admin.deposit.show', parameters: $deposit) }}"
                            class="flex-1 inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition">
                            Edit
                        </a>
                        <button x-data
                            @click.prevent="if (confirm('Are you sure you want to delete this deposit?')) { $wire.delete({{ $deposit->id }}) }"
                            class="flex-1 inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg text-white bg-red-600 hover:bg-red-700 transition">
                            Delete
                        </button>
                    </div>

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

        {{-- FOOTER / PAGINATION --}}
        <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);">

                <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>
                    <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>

                <div class="w-full md:w-auto text-center">{{ $this->deposits->links() }}</div>
            </div>
        </x-slot>

    </x-table.wrapper>


</div>
