<?php

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

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

    public $perPage = 10;
    public int $page = 1;
    public string $search = '';
    public ?string $filterType = null; // 'local', 'international', or null = all
    public string $currencySymbol = '$';

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

    public function updatedPerPage()
    {
        $this->resetPage();
    }

    public function setFilterType(?string $type)
    {
        $this->filterType = $type;
        $this->resetPage();
    }

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

        $query = Transfer::query()->with(['account.profile.user']);

        if ($this->filterType) {
            $query->where('type', $this->filterType);
        }

        // 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();
    }
    public function delete($id)
    {
        Transfer::findOrFail($id)->delete();
        $this->dispatch('showToast', message: 'Transfer successfully deleted', type: 'success');
    }
};
?>

<div class="space-y-5 py-5">

    {{-- Page Header --}}
    <x-page-header title="Transfers Management"
        subtitle="Overview of all user transfers, including local and international, with status, amount, and transaction history."
        back-url="{{ route('admin.dashboard') }}">
    </x-page-header>

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

        {{-- SEARCH --}}
        <x-slot name="search">
            <div class="flex items-center justify-between gap-2 flex-wrap">
                <div class="w-full md:w-1/3 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 user, ID, amount"
                        class="w-full pl-10 pr-4 py-2 rounded-md border bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700 focus:ring-2 focus:ring-sky-600 transition" />
                </div>

                {{-- Filter Tabs --}}
                <div class="flex gap-2 mb-3">

                    <!-- All Transfers -->
                    <x-button variant="{{ $filterType === null ? 'primary' : 'subtle' }}"
                        wire:click="$set('filterType', null)">
                        All
                    </x-button>

                    <!-- Local Transfers -->
                    <x-button variant="{{ $filterType === 'local' ? 'primary' : 'subtle' }}"
                        wire:click="$set('filterType', 'local')">
                        Local
                    </x-button>

                    <!-- International Transfers -->
                    <x-button variant="{{ $filterType === 'international' ? 'primary' : 'subtle' }}"
                        wire:click="$set('filterType', 'international')">
                        International
                    </x-button>

                </div>
            </div>
        </x-slot>

        {{-- HEADERS --}}
        <x-slot name="head">
            <x-table.head label="Transfer ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="User" />
            <x-table.head label="Type" field="type" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Fee" field="fee" 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="Created" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        {{-- BODY (DESKTOP) --}}
        <x-slot name="body">
            @forelse ($this->transfers as $transfer)
                @php
                    $account = $transfer->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-{{ $transfer->id }}" class="hover:shadow-lg rounded-lg mb-2">

                    {{-- Transfer ID --}}
                    <x-table.cell>{{ $transfer->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>


                    {{-- Type --}}
                    <x-table.cell>{{ ucfirst($transfer->type) }}</x-table.cell>

                    {{-- Amount / Fee / Total --}}
                    <x-table.cell>{{ $currencySymbol }}{{ number_format($transfer->amount, 2) }}</x-table.cell>
                    <x-table.cell>{{ $currencySymbol }}{{ number_format($transfer->fee, 2) }}</x-table.cell>
                    <x-table.cell>{{ $currencySymbol }}{{ number_format($transfer->total, 2) }}</x-table.cell>

                    {{-- Status --}}
                    <x-table.cell>
                        @if ($transfer->status === \App\Models\Transfer::STATUS_COMPLETED)
                            <span class="px-2 py-1 rounded-full bg-green-500 text-white text-xs">Completed</span>
                        @elseif ($transfer->status === \App\Models\Transfer::STATUS_FAILED)
                            <span class="px-2 py-1 rounded-full bg-red-500 text-white text-xs">Failed</span>
                        @else
                            <span class="px-2 py-1 rounded-full bg-yellow-400 text-black text-xs">Pending</span>
                        @endif
                    </x-table.cell>

                    {{-- Created --}}
                    <x-table.cell>{{ $transfer->created_at->diffForHumans() }}</x-table.cell>

                    {{-- Actions --}}
                    <x-table.cell class="flex gap-2">
                        <a href="{{ route('admin.transfer.show', $transfer) }}"
                            class="px-3 py-1 text-sm rounded-md bg-blue-600 text-white hover:bg-blue-700">View</a>

                        <button
                            @click.prevent="if(confirm('Delete this transfer?')){ $wire.delete({{ $transfer->id }}) }"
                            class="px-3 py-1 text-sm rounded-md bg-red-600 text-white hover:bg-red-700">Delete</button>
                    </x-table.cell>

                </x-table.row>
            @empty
                <tr>
                    <td colspan="9" class="text-center py-10 text-gray-400">No transfers found</td>
                </tr>
            @endforelse
        </x-slot>

        {{-- BODY (MOBILE) --}}
        <x-slot name="mobile">
            @forelse ($this->transfers as $transfer)
                @php
                    $account = $transfer->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 Info --}}
                    <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>


                    {{-- Transfer Details --}}
                    <div class="flex flex-col text-sm text-gray-700 dark:text-gray-300 space-y-1">
                        <div class="flex justify-between"><span>Type:</span><span>{{ ucfirst($transfer->type) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Amount:</span><span>{{ $currencySymbol }}{{ number_format($transfer->amount, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Fee:</span><span>{{ $currencySymbol }}{{ number_format($transfer->fee, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Total:</span><span>{{ $currencySymbol }}{{ number_format($transfer->total, 2) }}</span>
                        </div>
                        <div class="flex justify-between"><span>Status:</span>
                            @php
                                $statusClasses = match ($transfer->status) {
                                    Transfer::STATUS_COMPLETED => 'bg-green-100 text-green-800',
                                    Transfer::STATUS_FAILED => 'bg-red-100 text-red-800',
                                    default => 'bg-yellow-100 text-yellow-800',
                                };

                                $statusText = match ($transfer->status) {
                                    Transfer::STATUS_COMPLETED => 'Approved',
                                    Transfer::STATUS_FAILED => '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>Created:</span><span>{{ $transfer->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.transfer.show', $transfer) }}"
                            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">View</a>

                        <button
                            @click.prevent="if(confirm('Delete this transfer?')){ $wire.delete({{ $transfer->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 transfers found</div>
            @endforelse
        </x-slot>

        {{-- Pagination --}}
        {{-- 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->transfers->links() }}</div>
            </div>
        </x-slot>

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