<?php

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

new #[Layout('layouts::base')] class extends Component {
    public Transfer $transfer;
    use WithPagination, WithTableHelpers;
    public string $currencySymbol = '$';
    public array $currencies = [];
    public $perPage = 10;
    public int $page = 1;

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

    public function mount(Transfer $transfer)
    {
        $this->transfer = $transfer;
        $profileCurrency = $withdrawal->account?->profile?->currency ?? 'USD';
        $this->currencySymbol = \App\Support\Currency::symbol($profileCurrency);

        $this->loadCurrencies();
    }
    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }
    #[Computed]
    public function transfers()
    {
        $query = Transfer::query()
            ->with(['account.profile.user'])
            ->where('account_id', $this->transfer->account_id) // same user
            ->where('id', '!=', $this->transfer->id); // exclude current withdrawal

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

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

    public function loadCurrencies(): void
    {
        $this->currencies = \Illuminate\Support\Facades\Cache::rememberForever('currencies_json', function () {
            return collect(json_decode(file_get_contents(resource_path('data/currencies.json')), true))
                ->sortBy('name')
                ->values()
                ->toArray();
        });
    }

    public function approveTransferAction(): void
    {
        try {
            app(TransferHandler::class)->approveTransfer($this->transfer);

            $this->transfer = $this->transfer->fresh();

            $this->dispatch('notification-sent');
            $this->dispatch('showToast', message: 'Transfer approved successfully!', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function rejectTransferAction(): void
    {
        try {
            app(TransferHandler::class)->rejectTransfer($this->transfer);

            $this->transfer = $this->transfer->fresh();

            $this->dispatch('showToast', message: 'Transfer rejected successfully!', type: 'success');
            $this->dispatch('notification-sent');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }
};
?>

<div class="space-y-8 py-6">

    {{-- Page Header --}}
    <x-page-header title="Transfer #{{ $transfer->id }}" subtitle="Approve or review transfer details"
        rightText="Back to List" back-url="{{ route('admin.transfer.index') }}" />

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

        {{-- ================= Transfer Summary (Hero Section) ================= --}}
        <div
            class="bg-linear-to-r from-sky-500 to-purple-500 text-white rounded-2xl shadow-lg p-6 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div>
                <h2 class="text-2xl font-bold">Transfer #{{ $transfer->id }}</h2>
                <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>

            <div class="flex flex-col sm:flex-row items-center sm:space-x-6 gap-2">
                <div class="text-center sm:text-right">
                    <p class="text-xl font-bold">
                        {{ $transfer->account ? \App\Support\Currency::symbol($transfer->account->profile->currency) . number_format($transfer->total, 2) : '-' }}
                    </p>
                    <p class="text-sm opacity-80">Total Amount</p>
                </div>

                @if ($transfer->status === Transfer::STATUS_PENDING)
                    <div class="flex space-x-2">
                        <x-flux::button wire:click="approveTransferAction" variant="primary" color="green">
                            Approve
                        </x-flux::button>
                        <x-flux::button wire:click="rejectTransferAction" variant="danger">
                            Reject
                        </x-flux::button>
                    </div>
                @endif
            </div>
        </div>

        {{-- ================= Main Content: Left + Right Columns ================= --}}
        <div class="lg:flex lg:space-x-6">

            {{-- ================= Left Column: Transfer Details ================= --}}
            <div class="lg:flex-1 space-y-6">

                {{-- Metrics Cards --}}
                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">

                    <x-transaction-card icon="flux::icon.currency-dollar" bgColor="bg-sky-100"
                        darkBgColor="dark:bg-sky-800" textColor="text-sky-600" darkTextColor="dark:text-sky-300"
                        label="Amount"
                        value="{{ $transfer->account ? \App\Support\Currency::symbol($transfer->account->profile->currency) . number_format($transfer->amount, 2) : '-' }}" />

                    <x-transaction-card icon="flux::icon.credit-card" bgColor="bg-red-100" darkBgColor="dark:bg-red-800"
                        textColor="text-red-600" darkTextColor="dark:text-red-300" label="Fee"
                        value="{{ $transfer->account ? \App\Support\Currency::symbol($transfer->account->profile->currency) . number_format($transfer->fee, 2) : '-' }}" />

                    <x-transaction-card icon="flux::icon.banknotes" bgColor="bg-green-100"
                        darkBgColor="dark:bg-green-800" textColor="text-green-600" darkTextColor="dark:text-green-300"
                        label="Total"
                        value="{{ $transfer->account ? \App\Support\Currency::symbol($transfer->account->profile->currency) . number_format($transfer->total, 2) : '-' }}" />

                    <x-transaction-card icon="flux::icon.calendar" bgColor="bg-yellow-100"
                        darkBgColor="dark:bg-yellow-800" textColor="text-yellow-600"
                        darkTextColor="dark:text-yellow-300" label="Requested"
                        value="{{ $transfer->created_at->diffForHumans() }}" />
                </div>

                {{-- Payment & Account Info --}}
                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">

                    <x-transaction-card icon="flux::icon.wallet" bgColor="bg-indigo-100"
                        darkBgColor="dark:bg-indigo-800" textColor="text-indigo-600"
                        darkTextColor="dark:text-indigo-300" label="Payment Method"
                        value="{{ $transfer->paymentMethod->name ?? 'N/A' }}" />

                    <x-transaction-card icon="flux::icon.user-circle" bgColor="bg-purple-100"
                        darkBgColor="dark:bg-purple-800" textColor="text-purple-600"
                        darkTextColor="dark:text-purple-300" label="Account"
                        value="{{ $transfer->account?->account_number ?? 'N/A' }}" />

                    <x-transaction-card icon="flux::icon.document-currency-bangladeshi" bgColor="bg-teal-100"
                        darkBgColor="dark:bg-teal-800" textColor="text-teal-600" darkTextColor="dark:text-teal-300"
                        label="Currency" value="{{ $transfer->account?->profile?->currency ?? 'USD' }}" />

                    <x-transaction-card icon="flux::icon.arrow-trending-up" bgColor="bg-pink-100"
                        darkBgColor="dark:bg-pink-800" textColor="text-pink-600" darkTextColor="dark:text-pink-300"
                        label="Type" value="{{ ucfirst($transfer->type) }}" />
                </div>

                {{-- ---------- Timestamps ---------- --}}
                <div class=" text-sm text-gray-600 dark:text-gray-400">
                    <div class="bg-gray-100 dark:bg-gray-900 p-4 rounded-xl shadow-sm">
                        <p class="font-medium">Last Updated</p>
                        <p>{{ $transfer->updated_at->toDayDateTimeString() }}</p>
                    </div>
                </div>
            </div>

            {{-- ================= Right Column: User Profile ================= --}}
            <div class="lg:w-1/3 mt-6 lg:mt-0 space-y-6 sticky top-6">

                @php
                    $user = $transfer->account->profile->user;
                    $avatar = $transfer->account->profile->profile_photo
                        ? Storage::disk('public')->url($transfer->account->profile->profile_photo)
                        : null;
                @endphp

                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 flex flex-col items-center text-center space-y-4">

                    <div
                        class="w-28 h-28 rounded-full overflow-hidden border-4 border-sky-500 flex items-center justify-center text-4xl font-semibold bg-gray-300 dark:bg-gray-700">
                        @if ($avatar)
                            <img src="{{ $avatar }}" alt="User Avatar" class="w-full h-full object-cover">
                        @else
                            {{ strtoupper(substr($user->name ?? 'N/A', 0, 1)) }}
                        @endif
                    </div>

                    <h4 class="font-bold text-lg text-gray-900 dark:text-white">{{ $user->name ?? 'N/A' }}</h4>
                    <p class="text-gray-500 dark:text-gray-400 lowercase">{{ $user->email ?? 'N/A' }}</p>
                    <span
                        class="px-3 py-1 bg-sky-100 dark:bg-sky-700 text-sky-800 dark:text-white rounded-full text-sm font-medium">
                        KYC: {{ ucfirst($user->kyc_status) }}
                    </span>

                    <a href="{{ route('admin.users.show', $user) }}"
                        class="mt-3 px-5 py-2 bg-sky-600 hover:bg-sky-700 text-white font-semibold rounded-lg transition">
                        View Profile
                    </a>

                </div>


            </div>

        </div>
    </div>

    {{-- ===== Other Transfers by User --}}
    <div class="space-y-5 py-5">
        <x-page-header title="Other Transfers by User"
            subtitle="All transfers by this user, excluding the current one." />
        <x-table.wrapper :items="$this->transfers">

            {{-- 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="Transfer ID" field="id" 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="Type" field="type" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Requested" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Action" />
            </x-slot>

            {{-- BODY --}}
            <x-slot name="body">
                @forelse ($this->transfers as $t)
                    @php
                        $acc = $t->account;
                        $profile = $acc?->profile;
                        $user = $profile?->user;
                        $currencySymbol = $profile ? \App\Support\Currency::symbol($profile->currency) : '$';
                    @endphp
                    <x-table.row wire:key="row-{{ $t->id }}">
                        <x-table.cell>{{ $t->id }}</x-table.cell>
                        <x-table.cell>{{ $currencySymbol }}{{ number_format($t->amount, 2) }}</x-table.cell>
                        <x-table.cell>{{ $currencySymbol }}{{ number_format($t->fee, 2) }}</x-table.cell>
                        <x-table.cell>{{ $currencySymbol }}{{ number_format($t->total, 2) }}</x-table.cell>
                        <x-table.cell>{{ ucfirst($t->type) }}</x-table.cell>
                        <x-table.cell>
                            @if ($t->status === Transfer::STATUS_COMPLETED)
                                <span class="px-2 py-1 rounded-full bg-green-500 text-white text-xs">Completed</span>
                            @elseif ($t->status === 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>
                        <x-table.cell>{{ $t->created_at->diffForHumans() }}</x-table.cell>
                        <x-table.cell>
                            <a href="{{ route('admin.transfer.show', $t) }}"
                                class="px-3 py-1.5 text-sm rounded-md text-white bg-blue-600 hover:bg-blue-700">View</a>
                        </x-table.cell>
                    </x-table.row>
                @empty
                    <tr>
                        <td colspan="8" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">No
                            transfers found</td>
                    </tr>
                @endforelse
            </x-slot>

            <x-slot name="mobile">
                @forelse ($this->transfers as $t)
                    @php
                        $acc = $t->account;
                        $profile = $acc?->profile;
                        $user = $profile?->user;
                        $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">

                        {{-- 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>Amount:</span>
                                <span>{{ $currencySymbol }}{{ number_format($t->amount, 2) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Fee:</span>
                                <span>{{ $currencySymbol }}{{ number_format($t->fee, 2) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Total:</span>
                                <span>{{ $currencySymbol }}{{ number_format($t->total, 2) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Type:</span>
                                <span>{{ ucfirst($t->type) }}</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>Requested:</span>
                                <span>{{ $t->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', $t) }}"
                                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>
                        </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>


            {{-- FOOTER / PAGINATION --}}
            <x-slot name="footer">
                <div class="w-full mt-6">
                    {{ $this->transfers->links() }}
                </div>
            </x-slot>

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