<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\Withdrawal;
use App\Services\TransactionHandler;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;

new #[Layout('layouts::base')] class extends Component {
    use WithPagination, WithTableHelpers;
    public Withdrawal $withdrawal;
    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(Withdrawal $withdrawal)
    {
        $this->withdrawal = $withdrawal;

        $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 withdrawals()
    {
        $query = Withdrawal::query()
            ->where('account_id', $this->withdrawal->account_id) // same user
            ->where('id', '!=', $this->withdrawal->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();
        });
    }

    /**
     * Approve withdrawal using the new TransactionHandler service
     */
    public function approveWithdrawal(): void
    {
        try {
            $transaction = app(TransactionHandler::class)->approveWithdrawal($this->withdrawal);

            if (!$transaction) {
                $this->dispatch('showToast', message: 'Withdrawal already processed or not pending.', type: 'warning');
                return;
            }
            $this->withdrawal = $this->withdrawal->fresh();
            $this->dispatch('notification-sent');
            $this->dispatch('showToast', message: 'Withdrawal approved successfully!', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Reject withdrawal using the new TransactionHandler service
     */
    public function rejectWithdrawal(): void
    {
        app(TransactionHandler::class)->rejectTransaction($this->withdrawal);

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

        $this->dispatch('showToast', message: 'Withdrawal rejected safely!', type: 'success');
    }
};
?>

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

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

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

        {{-- ================= Withdrawal 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">Withdrawal #{{ $withdrawal->id }}</h2>
                <div class="flex items-center justify-between">
                    <span>Status:</span>
                    @php
                        $statusClasses = match ($withdrawal->status) {
                            Withdrawal::STATUS_APPROVED => 'bg-green-100 text-green-800',
                            Withdrawal::STATUS_REJECTED => 'bg-red-100 text-red-800',
                            default => 'bg-yellow-100 text-yellow-800',
                        };

                        $statusText = match ($withdrawal->status) {
                            Withdrawal::STATUS_APPROVED => 'Approved',
                            Withdrawal::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>

            <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">
                        {{ $withdrawal->account ? \App\Support\Currency::symbol($withdrawal->account->profile->currency) . number_format($withdrawal->total, 2) : '-' }}
                    </p>
                    <p class="text-sm opacity-80">Total Amount</p>
                </div>

                @if ($withdrawal->isPending())
                    <div class="flex space-x-2">
                        <x-flux::button wire:click="approveWithdrawal" variant="primary" color="green">
                            Approve
                        </x-flux::button>
                        <x-flux::button wire:click="rejectWithdrawal" 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: Withdrawal 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="{{ $withdrawal->account ? \App\Support\Currency::symbol($withdrawal->account->profile->currency) . number_format($withdrawal->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="{{ $withdrawal->account ? \App\Support\Currency::symbol($withdrawal->account->profile->currency) . number_format($withdrawal->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="{{ $withdrawal->account ? \App\Support\Currency::symbol($withdrawal->account->profile->currency) . number_format($withdrawal->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="{{ $withdrawal->created_at->diffForHumans() }}" />
                </div>

                <div class="flex items-end justify-end">
                    @if ($withdrawal->paymentMethod)
                        <a href="{{ route('admin.dashboard', ['paymentMethodId' => $withdrawal->paymentMethod->id]) }}"
                            class="text-blue-600 dark:text-blue-400 font-semibold hover:underline">
                            View withdrawal method Information
                        </a>
                    @else
                        <span class="italic text-gray-400">N/A</span>
                    @endif
                </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="{{ $withdrawal->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="{{ $withdrawal->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="{{ $withdrawal->account?->profile?->currency ?? 'USD' }}" />

                    @if ($withdrawal->account?->profile?->user?->referrer)
                        <x-transaction-card icon="flux::icon.user-plus" bgColor="bg-pink-100"
                            darkBgColor="dark:bg-pink-800" textColor="text-pink-600" darkTextColor="dark:text-pink-300"
                            label="Referrer" value="{{ $withdrawal->account->profile->user->referrer->name }}" />
                    @endif
                </div>

            </div>

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

                <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">
                    @php
                        $user = $withdrawal->account->profile->user;
                        $avatar = $withdrawal->account->profile->profile_photo
                            ? Storage::disk('public')->url($withdrawal->account->profile->profile_photo)
                            : null;
                    @endphp

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

                {{-- ---------- 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>{{ $withdrawal->updated_at->toDayDateTimeString() }}</p>
                    </div>
                </div>

            </div>

        </div>
    </div>

    {{-- ===== Other Withdrawals Made By User --}}

    <div class="space-y-5 py-5">
        <x-page-header title="Other Withdrawals by User"
            subtitle="All withdrawals by this user, excluding the current one.">
        </x-page-header>


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

            {{-- 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="withdrawal ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Charge" 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="Joined" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Action" />
            </x-slot>

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

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


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

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

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

                        {{-- Status --}}
                        <x-table.cell>
                            @if ($withdrawal->status === withdrawal::STATUS_APPROVED)
                                <span class="px-2 py-1 rounded-full bg-green-500 text-white text-xs">Approved</span>
                            @elseif ($withdrawal->status === withdrawal::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>{{ $withdrawal->created_at->diffForHumans() }}</x-table.cell>

                        {{-- Actions --}}
                        <x-table.cell>
                            <a href="{{ route('admin.withdrawal.show', parameters: $withdrawal) }}"
                                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>

                        </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 withdrawals found
                        </td>
                    </tr>
                @endforelse
            </x-slot>

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

                        {{-- 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($withdrawal->amount, 2) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Total:</span>
                                <span>{{ $currencySymbol }}{{ number_format($withdrawal->total, 2) }}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span>Status:</span>
                                @php
                                    $statusClasses = match ($withdrawal->status) {
                                        Withdrawal::STATUS_APPROVED => 'bg-green-100 text-green-800',
                                        Withdrawal::STATUS_REJECTED => 'bg-red-100 text-red-800',
                                        default => 'bg-yellow-100 text-yellow-800',
                                    };

                                    $statusText = match ($withdrawal->status) {
                                        Withdrawal::STATUS_APPROVED => 'Approved',
                                        Withdrawal::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>{{ $withdrawal->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.withdrawal.show', parameters: $withdrawal) }}"
                                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>

                        </div>

                    </x-table.mobile-card>
                @empty
                    <div class="px-6 py-6 text-center text-gray-400 dark:text-gray-500">
                        No withdrawals 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->withdrawals->links() }}</div>
                </div>
            </x-slot>

        </x-table.wrapper>


    </div>


</div>
